Some work is too slow to do while a customer waits, like emailing a receipt or packing an order. A shop writes these jobs into a queue, and a worker does them later, oldest first. A Redis list makes a good queue: it keeps its values in order, and you add at one end and take from the other.
r.rpush(key, value, ...) adds values at the right end, the back, and makes the list if it isn't there. r.lpop(key) removes the first value, at the front, and gives it back, or None when the list is empty. r.llen(key) gives back how many values the list holds. Think of append, pop(0) and len() on a Python list.
To look without taking, r.lrange(key, start, end) gives back a Python list of the values between two positions. -1 means the last one, and unlike a Python slice, the end is included.
r.rpush("tasks", "wash", "dry")
r.rpush("tasks", "fold")
print(r.lrange("tasks", 0, 1)) # ['wash', 'dry']
print(r.lpop("tasks")) # wash
print(r.llen("tasks")) # 2
This lesson runs on an in-memory stand-in for Redis that starts empty; the same code runs unchanged on a real Redis server. Your script prints the first three lines below, then the check prints what is still waiting:
Waiting: 3 Queue: ['email receipt 1', 'email receipt 2', 'pack order 3'] Doing: email receipt 1 Left: ['email receipt 2', 'pack order 3']
Your task: push "email receipt 1" and "email receipt 2" onto the "jobs" list, then "pack order 3". Print how many jobs wait, print the whole queue without taking anything, and take the first job off the front.
Assignment
Follow the Coding Tutorial to fill a job queue with rpush, look at it with llen and lrange, and take the oldest job with lpop.
Hint
Push at the right, pop at the left: that gives first in, first out. lrange(key, 0, -1) reads every value and takes nothing.
Free plan: 30 tutor messages. PRO is unlimited.
