From 48cee215afb92acb10c6260b39017890e21f70c9 Mon Sep 17 00:00:00 2001 From: Vincent Driessen Date: Mon, 21 May 2012 08:08:59 +0200 Subject: [PATCH] Rewrite of the connection setup. I'd want to advice against using `use_connection()` more, as the connection setup is less explicit, and also pollutes global memory. Because, well: $ python -m this | head -n4 | tail -n1 ;) --- examples/run_example.py | 58 +++++++++++++++++++++++------------------ examples/run_worker.py | 10 +++---- 2 files changed, 37 insertions(+), 31 deletions(-) diff --git a/examples/run_example.py b/examples/run_example.py index 5c52ec7..cbcc6e9 100644 --- a/examples/run_example.py +++ b/examples/run_example.py @@ -1,34 +1,40 @@ import os import time -from rq import Queue, use_connection +from rq import Queue, Connection from fib import slow_fib -# Tell RQ what Redis connection to use -use_connection() -# Range of Fibonacci numbers to compute -fib_range = range(20, 34) -# Kick off the tasks asynchronously -async_results = {} -q = Queue() -for x in fib_range: - async_results[x] = q.enqueue(slow_fib, x) +def main(): + # Range of Fibonacci numbers to compute + fib_range = range(20, 34) -start_time = time.time() -done = False -while not done: - os.system('clear') - print 'Asynchronously: (now = %.2f)' % (time.time() - start_time) - done = True + # Kick off the tasks asynchronously + async_results = {} + q = Queue() for x in fib_range: - result = async_results[x].return_value - if result is None: - done = False - result = '(calculating)' - print 'fib(%d) = %s' % (x, result) - print '' - print 'To start the actual in the background, run a worker:' - print ' python examples/run_worker.py' - time.sleep(0.2) + async_results[x] = q.enqueue(slow_fib, x) -print 'Done' + start_time = time.time() + done = False + while not done: + os.system('clear') + print 'Asynchronously: (now = %.2f)' % (time.time() - start_time) + done = True + for x in fib_range: + result = async_results[x].return_value + if result is None: + done = False + result = '(calculating)' + print 'fib(%d) = %s' % (x, result) + print '' + print 'To start the actual in the background, run a worker:' + print ' python examples/run_worker.py' + time.sleep(0.2) + + print 'Done' + + +if __name__ == '__main__': + # Tell RQ what Redis connection to use + with Connection(): + main() diff --git a/examples/run_worker.py b/examples/run_worker.py index 38af522..7c8adae 100644 --- a/examples/run_worker.py +++ b/examples/run_worker.py @@ -1,8 +1,8 @@ -from rq import Queue, Worker, use_connection +from rq import Queue, Worker, Connection -# Tell rq what Redis connection to use -use_connection() if __name__ == '__main__': - q = Queue() - Worker(q).work() + # Tell rq what Redis connection to use + with Connection(): + q = Queue() + Worker(q).work()