File: run_example.py

package info (click to toggle)
python-rq 2.5-1
  • links: PTS, VCS
  • area: main
  • in suites: forky
  • size: 2,536 kB
  • sloc: python: 13,369; makefile: 22; sh: 19
file content (49 lines) | stat: -rw-r--r-- 1,247 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import os
import time

from fib import slow_fib
from redis import Redis

from rq import Queue
from rq.job import JobStatus


def enqueue(connection):
    # Range of Fibonacci numbers to compute
    fib_range = range(20, 34)

    # Kick off the tasks asynchronously
    q = Queue(connection=connection)
    jobs = [q.enqueue(slow_fib, arg) for arg in fib_range]
    return jobs


def wait_for_all(jobs):
    start_time = time.time()
    done = False
    while not done:
        os.system('clear')
        print('Asynchronously: (now = %.2f)' % (time.time() - start_time,))
        done = True
        for job in jobs:
            status = job.get_status()
            if status is JobStatus.FINISHED:
                result = job.return_value()
            else:
                result = '(%s)' % status.name
                done = False
            (arg,) = job.args
            print('fib(%d) = %s' % (arg, result))
        print('')
        print('To start the actual in the background, run a worker:')
        print('    $ rq worker')
        time.sleep(0.2)

    print('Done')


if __name__ == '__main__':
    # Tell RQ what Redis connection to use
    with Redis() as redis_conn:
        jobs = enqueue(redis_conn)
        wait_for_all(jobs)