Debian Codegraph @

examples/resultgraph/tasks.py

raw
1 # Example::
2 # >>> R = A.apply_async()
3 # >>> list(joinall(R))
4 # [['A 0', 'A 1', 'A 2', 'A 3', 'A 4', 'A 5', 'A 6', 'A 7', 'A 8', 'A 9'],
5 # ['B 0', 'B 1', 'B 2', 'B 3', 'B 4', 'B 5', 'B 6', 'B 7', 'B 8', 'B 9'],
6 # ['C 0', 'C 1', 'C 2', 'C 3', 'C 4', 'C 5', 'C 6', 'C 7', 'C 8', 'C 9'],
7 # ['D 0', 'D 1', 'D 2', 'D 3', 'D 4', 'D 5', 'D 6', 'D 7', 'D 8', 'D 9'],
8 # ['E 0', 'E 1', 'E 2', 'E 3', 'E 4', 'E 5', 'E 6', 'E 7', 'E 8', 'E 9'],
9 # ['F 0', 'F 1', 'F 2', 'F 3', 'F 4', 'F 5', 'F 6', 'F 7', 'F 8', 'F 9'],
10 # ['G 0', 'G 1', 'G 2', 'G 3', 'G 4', 'G 5', 'G 6', 'G 7', 'G 8', 'G 9'],
11 # ['H 0', 'H 1', 'H 2', 'H 3', 'H 4', 'H 5', 'H 6', 'H 7', 'H 8', 'H 9']]
12 #
13 #
14 # Joining the graph asynchronously with a callback
15 # (Note: only two levels, the deps are considered final
16 # when the second task is ready).
17 #
18 # >>> unlock_graph.apply_async((A.apply_async(),
19 # ... A_callback.s()), countdown=1)
20
21 from collections import deque
22
23 from celery import chord, group, signature, task, uuid
24 from celery.result import AsyncResult, ResultSet, allow_join_result
25
26
27 @task()
28 def add(x, y):
29 return x + y
30
31
32 @task()
33 def make_request(id, url):
34 print(f'-get: {url!r}')
35 return url
36
37
38 @task()
39 def B_callback(urls, id):
40 print(f'-batch {id} done')
41 return urls
42
43
44 @task()
45 def B(id):
46 return chord(
47 make_request.s(id, f'{id} {i!r}')
48 for i in range(10)
49 )(B_callback.s(id))
50
51
52 @task()
53 def A():
54 return group(B.s(c) for c in 'ABCDEFGH').apply_async()
55
56
57 def joinall(R, timeout=None, propagate=True):
58 stack = deque([R])
59
60 try:
61 use_native = joinall.backend.supports_native_join
62 except AttributeError:
63 use_native = False
64
65 while stack:
66 res = stack.popleft()
67 if isinstance(res, ResultSet):
68 j = res.join_native if use_native else res.join
69 stack.extend(j(timeout=timeout, propagate=propagate))
70 elif isinstance(res, AsyncResult):
71 stack.append(res.get(timeout=timeout, propagate=propagate))
72 else:
73 yield res
74
75
76 @task()
77 def unlock_graph(result, callback,
78 interval=1, propagate=False, max_retries=None):
79 if result.ready():
80 second_level_res = result.get()
81 if second_level_res.ready():
82 with allow_join_result():
83 signature(callback).delay(list(joinall(
84 second_level_res, propagate=propagate)))
85 else:
86 unlock_graph.retry(countdown=interval, max_retries=max_retries)
87
88
89 @task()
90 def A_callback(res):
91 print(f'-everything done: {res!r}')
92 return res
93
94
95 class chord2:
96
97 def __init__(self, tasks, **options):
98 self.tasks = tasks
99 self.options = options
100
101 def __call__(self, body, **options):
102 body.options.setdefault('task_id', uuid())
103 unlock_graph.apply_async()