From 4d9c20d5d9ea274929af55ed17f5523547f84367 Mon Sep 17 00:00:00 2001 From: Vincent Driessen Date: Mon, 14 Apr 2014 11:26:02 +0200 Subject: [PATCH] Reimplement Queue.empty() in a Lua script. This makes the .empty() function perform all the computing in Redis itself, rather than in Python. This is both atomic, and faster. --- rq/queue.py | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/rq/queue.py b/rq/queue.py index 49d43d7..2f725e3 100644 --- a/rq/queue.py +++ b/rq/queue.py @@ -65,10 +65,25 @@ class Queue(object): def empty(self): """Removes all messages on the queue.""" - job_list = self.get_jobs() - self.connection.delete(self.key) - for job in job_list: - job.cancel() + script = b""" + local prefix = "rq:job:" + local q = KEYS[1] + local count = 0 + while true do + local job_id = redis.call("lpop", q) + if job_id == false then + break + end + + -- Delete the relevant keys + redis.call("del", prefix..job_id) + redis.call("del", prefix..job_id..":dependents") + count = count + 1 + end + return count + """ + script = self.connection.register_script(script) + return script(keys=[self.key]) def is_empty(self): """Returns whether the current queue is empty."""