canvas.rst 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072
  1. .. _guide-canvas:
  2. ==============================
  3. Canvas: Designing Work-flows
  4. ==============================
  5. .. contents::
  6. :local:
  7. :depth: 2
  8. .. _canvas-subtasks:
  9. .. _canvas-signatures:
  10. Signatures
  11. ==========
  12. .. versionadded:: 2.0
  13. You just learned how to call a task using the tasks ``delay`` method
  14. in the :ref:`calling <guide-calling>` guide, and this is often all you need,
  15. but sometimes you may want to pass the signature of a task invocation to
  16. another process or as an argument to another function.
  17. A :func:`~celery.signature` wraps the arguments, keyword arguments, and execution options
  18. of a single task invocation in a way such that it can be passed to functions
  19. or even serialized and sent across the wire.
  20. - You can create a signature for the ``add`` task using its name like this:
  21. .. code-block:: pycon
  22. >>> from celery import signature
  23. >>> signature('tasks.add', args=(2, 2), countdown=10)
  24. tasks.add(2, 2)
  25. This task has a signature of arity 2 (two arguments): ``(2, 2)``,
  26. and sets the countdown execution option to 10.
  27. - or you can create one using the task's ``signature`` method:
  28. .. code-block:: pycon
  29. >>> add.signature((2, 2), countdown=10)
  30. tasks.add(2, 2)
  31. - There's also a shortcut using star arguments:
  32. .. code-block:: pycon
  33. >>> add.s(2, 2)
  34. tasks.add(2, 2)
  35. - Keyword arguments are also supported:
  36. .. code-block:: pycon
  37. >>> add.s(2, 2, debug=True)
  38. tasks.add(2, 2, debug=True)
  39. - From any signature instance you can inspect the different fields:
  40. .. code-block:: pycon
  41. >>> s = add.signature((2, 2), {'debug': True}, countdown=10)
  42. >>> s.args
  43. (2, 2)
  44. >>> s.kwargs
  45. {'debug': True}
  46. >>> s.options
  47. {'countdown': 10}
  48. - It supports the "Calling API" of ``delay``,
  49. ``apply_async``, etc., including being called directly (``__call__``).
  50. Calling the signature will execute the task inline in the current process:
  51. .. code-block:: pycon
  52. >>> add(2, 2)
  53. 4
  54. >>> add.s(2, 2)()
  55. 4
  56. ``delay`` is our beloved shortcut to ``apply_async`` taking star-arguments:
  57. .. code-block:: pycon
  58. >>> result = add.delay(2, 2)
  59. >>> result.get()
  60. 4
  61. ``apply_async`` takes the same arguments as the
  62. :meth:`Task.apply_async <@Task.apply_async>` method:
  63. .. code-block:: pycon
  64. >>> add.apply_async(args, kwargs, **options)
  65. >>> add.signature(args, kwargs, **options).apply_async()
  66. >>> add.apply_async((2, 2), countdown=1)
  67. >>> add.signature((2, 2), countdown=1).apply_async()
  68. - You can't define options with :meth:`~@Task.s`, but a chaining
  69. ``set`` call takes care of that:
  70. .. code-block:: pycon
  71. >>> add.s(2, 2).set(countdown=1)
  72. proj.tasks.add(2, 2)
  73. Partials
  74. --------
  75. With a signature, you can execute the task in a worker:
  76. .. code-block:: pycon
  77. >>> add.s(2, 2).delay()
  78. >>> add.s(2, 2).apply_async(countdown=1)
  79. Or you can call it directly in the current process:
  80. .. code-block:: pycon
  81. >>> add.s(2, 2)()
  82. 4
  83. Specifying additional args, kwargs, or options to ``apply_async``/``delay``
  84. creates partials:
  85. - Any arguments added will be prepended to the args in the signature:
  86. .. code-block:: pycon
  87. >>> partial = add.s(2) # incomplete signature
  88. >>> partial.delay(4) # 4 + 2
  89. >>> partial.apply_async((4,)) # same
  90. - Any keyword arguments added will be merged with the kwargs in the signature,
  91. with the new keyword arguments taking precedence:
  92. .. code-block:: pycon
  93. >>> s = add.s(2, 2)
  94. >>> s.delay(debug=True) # -> add(2, 2, debug=True)
  95. >>> s.apply_async(kwargs={'debug': True}) # same
  96. - Any options added will be merged with the options in the signature,
  97. with the new options taking precedence:
  98. .. code-block:: pycon
  99. >>> s = add.signature((2, 2), countdown=10)
  100. >>> s.apply_async(countdown=1) # countdown is now 1
  101. You can also clone signatures to create derivatives:
  102. .. code-block:: pycon
  103. >>> s = add.s(2)
  104. proj.tasks.add(2)
  105. >>> s.clone(args=(4,), kwargs={'debug': True})
  106. proj.tasks.add(4, 2, debug=True)
  107. Immutability
  108. ------------
  109. .. versionadded:: 3.0
  110. Partials are meant to be used with callbacks, any tasks linked, or chord
  111. callbacks will be applied with the result of the parent task.
  112. Sometimes you want to specify a callback that doesn't take
  113. additional arguments, and in that case you can set the signature
  114. to be immutable:
  115. .. code-block:: pycon
  116. >>> add.apply_async((2, 2), link=reset_buffers.signature(immutable=True))
  117. The ``.si()`` shortcut can also be used to create immutable signatures:
  118. .. code-block:: pycon
  119. >>> add.apply_async((2, 2), link=reset_buffers.si())
  120. Only the execution options can be set when a signature is immutable,
  121. so it's not possible to call the signature with partial args/kwargs.
  122. .. note::
  123. In this tutorial I sometimes use the prefix operator `~` to signatures.
  124. You probably shouldn't use it in your production code, but it's a handy shortcut
  125. when experimenting in the Python shell:
  126. .. code-block:: pycon
  127. >>> ~sig
  128. >>> # is the same as
  129. >>> sig.delay().get()
  130. .. _canvas-callbacks:
  131. Callbacks
  132. ---------
  133. .. versionadded:: 3.0
  134. Callbacks can be added to any task using the ``link`` argument
  135. to ``apply_async``:
  136. .. code-block:: pycon
  137. add.apply_async((2, 2), link=other_task.s())
  138. The callback will only be applied if the task exited successfully,
  139. and it will be applied with the return value of the parent task as argument.
  140. As I mentioned earlier, any arguments you add to a signature,
  141. will be prepended to the arguments specified by the signature itself!
  142. If you have the signature:
  143. .. code-block:: pycon
  144. >>> sig = add.s(10)
  145. then `sig.delay(result)` becomes:
  146. .. code-block:: pycon
  147. >>> add.apply_async(args=(result, 10))
  148. ...
  149. Now let's call our ``add`` task with a callback using partial
  150. arguments:
  151. .. code-block:: pycon
  152. >>> add.apply_async((2, 2), link=add.s(8))
  153. As expected this will first launch one task calculating :math:`2 + 2`, then
  154. another task calculating :math:`4 + 8`.
  155. The Primitives
  156. ==============
  157. .. versionadded:: 3.0
  158. .. topic:: Overview
  159. - ``group``
  160. The group primitive is a signature that takes a list of tasks that should
  161. be applied in parallel.
  162. - ``chain``
  163. The chain primitive lets us link together signatures so that one is called
  164. after the other, essentially forming a *chain* of callbacks.
  165. - ``chord``
  166. A chord is just like a group but with a callback. A chord consists
  167. of a header group and a body, where the body is a task that should execute
  168. after all of the tasks in the header are complete.
  169. - ``map``
  170. The map primitive works like the built-in ``map`` function, but creates
  171. a temporary task where a list of arguments is applied to the task.
  172. For example, ``task.map([1, 2])`` -- results in a single task
  173. being called, applying the arguments in order to the task function so
  174. that the result is:
  175. .. code-block:: python
  176. res = [task(1), task(2)]
  177. - ``starmap``
  178. Works exactly like map except the arguments are applied as ``*args``.
  179. For example ``add.starmap([(2, 2), (4, 4)])`` results in a single
  180. task calling:
  181. .. code-block:: python
  182. res = [add(2, 2), add(4, 4)]
  183. - ``chunks``
  184. Chunking splits a long list of arguments into parts, for example
  185. the operation:
  186. .. code-block:: pycon
  187. >>> items = zip(xrange(1000), xrange(1000)) # 1000 items
  188. >>> add.chunks(items, 10)
  189. will split the list of items into chunks of 10, resulting in 100
  190. tasks (each processing 10 items in sequence).
  191. The primitives are also signature objects themselves, so that they can be combined
  192. in any number of ways to compose complex work-flows.
  193. Here's some examples:
  194. - Simple chain
  195. Here's a simple chain, the first task executes passing its return value
  196. to the next task in the chain, and so on.
  197. .. code-block:: pycon
  198. >>> from celery import chain
  199. >>> # 2 + 2 + 4 + 8
  200. >>> res = chain(add.s(2, 2), add.s(4), add.s(8))()
  201. >>> res.get()
  202. 16
  203. This can also be written using pipes:
  204. .. code-block:: pycon
  205. >>> (add.s(2, 2) | add.s(4) | add.s(8))().get()
  206. 16
  207. - Immutable signatures
  208. Signatures can be partial so arguments can be
  209. added to the existing arguments, but you may not always want that,
  210. for example if you don't want the result of the previous task in a chain.
  211. In that case you can mark the signature as immutable, so that the arguments
  212. cannot be changed:
  213. .. code-block:: pycon
  214. >>> add.signature((2, 2), immutable=True)
  215. There's also a ``.si()`` shortcut for this, and this is the preffered way of
  216. creating signatures:
  217. .. code-block:: pycon
  218. >>> add.si(2, 2)
  219. Now you can create a chain of independent tasks instead:
  220. .. code-block:: pycon
  221. >>> res = (add.si(2, 2) | add.si(4, 4) | add.si(8, 8))()
  222. >>> res.get()
  223. 16
  224. >>> res.parent.get()
  225. 8
  226. >>> res.parent.parent.get()
  227. 4
  228. - Simple group
  229. You can easily create a group of tasks to execute in parallel:
  230. .. code-block:: pycon
  231. >>> from celery import group
  232. >>> res = group(add.s(i, i) for i in xrange(10))()
  233. >>> res.get(timeout=1)
  234. [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
  235. - Simple chord
  236. The chord primitive enables us to add a callback to be called when
  237. all of the tasks in a group have finished executing. This is often
  238. required for algorithms that aren't *embarrassingly parallel*:
  239. .. code-block:: pycon
  240. >>> from celery import chord
  241. >>> res = chord((add.s(i, i) for i in xrange(10)), xsum.s())()
  242. >>> res.get()
  243. 90
  244. The above example creates 10 task that all start in parallel,
  245. and when all of them are complete the return values are combined
  246. into a list and sent to the ``xsum`` task.
  247. The body of a chord can also be immutable, so that the return value
  248. of the group isn't passed on to the callback:
  249. .. code-block:: pycon
  250. >>> chord((import_contact.s(c) for c in contacts),
  251. ... notify_complete.si(import_id)).apply_async()
  252. Note the use of ``.si`` above; this creates an immutable signature,
  253. meaning any new arguments passed (including to return value of the
  254. previous task) will be ignored.
  255. - Blow your mind by combining
  256. Chains can be partial too:
  257. .. code-block:: pycon
  258. >>> c1 = (add.s(4) | mul.s(8))
  259. # (16 + 4) * 8
  260. >>> res = c1(16)
  261. >>> res.get()
  262. 160
  263. this means that you can combine chains:
  264. .. code-block:: pycon
  265. # ((4 + 16) * 2 + 4) * 8
  266. >>> c2 = (add.s(4, 16) | mul.s(2) | (add.s(4) | mul.s(8)))
  267. >>> res = c2()
  268. >>> res.get()
  269. 352
  270. Chaining a group together with another task will automatically
  271. upgrade it to be a chord:
  272. .. code-block:: pycon
  273. >>> c3 = (group(add.s(i, i) for i in xrange(10)) | xsum.s())
  274. >>> res = c3()
  275. >>> res.get()
  276. 90
  277. Groups and chords accepts partial arguments too, so in a chain
  278. the return value of the previous task is forwarded to all tasks in the group:
  279. .. code-block:: pycon
  280. >>> new_user_workflow = (create_user.s() | group(
  281. ... import_contacts.s(),
  282. ... send_welcome_email.s()))
  283. ... new_user_workflow.delay(username='artv',
  284. ... first='Art',
  285. ... last='Vandelay',
  286. ... email='art@vandelay.com')
  287. If you don't want to forward arguments to the group then
  288. you can make the signatures in the group immutable:
  289. .. code-block:: pycon
  290. >>> res = (add.s(4, 4) | group(add.si(i, i) for i in xrange(10)))()
  291. >>> res.get()
  292. <GroupResult: de44df8c-821d-4c84-9a6a-44769c738f98 [
  293. bc01831b-9486-4e51-b046-480d7c9b78de,
  294. 2650a1b8-32bf-4771-a645-b0a35dcc791b,
  295. dcbee2a5-e92d-4b03-b6eb-7aec60fd30cf,
  296. 59f92e0a-23ea-41ce-9fad-8645a0e7759c,
  297. 26e1e707-eccf-4bf4-bbd8-1e1729c3cce3,
  298. 2d10a5f4-37f0-41b2-96ac-a973b1df024d,
  299. e13d3bdb-7ae3-4101-81a4-6f17ee21df2d,
  300. 104b2be0-7b75-44eb-ac8e-f9220bdfa140,
  301. c5c551a5-0386-4973-aa37-b65cbeb2624b,
  302. 83f72d71-4b71-428e-b604-6f16599a9f37]>
  303. >>> res.parent.get()
  304. 8
  305. .. _canvas-chain:
  306. Chains
  307. ------
  308. .. versionadded:: 3.0
  309. Tasks can be linked together: the linked task is called when the task
  310. returns successfully:
  311. .. code-block:: pycon
  312. >>> res = add.apply_async((2, 2), link=mul.s(16))
  313. >>> res.get()
  314. 64
  315. The linked task will be applied with the result of its parent
  316. task as the first argument. In the above case where the result was 64,
  317. this will result in ``mul(4, 16)``.
  318. The results will keep track of any subtasks called by the original task,
  319. and this can be accessed from the result instance:
  320. .. code-block:: pycon
  321. >>> res.children
  322. [<AsyncResult: 8c350acf-519d-4553-8a53-4ad3a5c5aeb4>]
  323. >>> res.children[0].get()
  324. 64
  325. The result instance also has a :meth:`~@AsyncResult.collect` method
  326. that treats the result as a graph, enabling you to iterate over
  327. the results:
  328. .. code-block:: pycon
  329. >>> list(res.collect())
  330. [(<AsyncResult: 7b720856-dc5f-4415-9134-5c89def5664e>, 4),
  331. (<AsyncResult: 8c350acf-519d-4553-8a53-4ad3a5c5aeb4>, 64)]
  332. By default :meth:`~@AsyncResult.collect` will raise an
  333. :exc:`~@IncompleteStream` exception if the graph isn't fully
  334. formed (one of the tasks hasn't completed yet),
  335. but you can get an intermediate representation of the graph
  336. too:
  337. .. code-block:: pycon
  338. >>> for result, value in res.collect(intermediate=True)):
  339. ....
  340. You can link together as many tasks as you like,
  341. and signatures can be linked too:
  342. .. code-block:: pycon
  343. >>> s = add.s(2, 2)
  344. >>> s.link(mul.s(4))
  345. >>> s.link(log_result.s())
  346. You can also add *error callbacks* using the `on_error` method:
  347. .. code-block:: pycon
  348. >>> add.s(2, 2).on_error(log_error.s()).delay()
  349. This will result in the following ``.apply_async`` call when the signature
  350. is applied:
  351. .. code-block:: pycon
  352. >>> add.apply_async((2, 2), link_error=log_error.s())
  353. The worker won't actually call the errback as a task, but will
  354. instead call the errback function directly so that the raw request, exception
  355. and traceback objects can be passed to it.
  356. Here's an example errback:
  357. .. code-block:: python
  358. from __future__ import print_function
  359. import os
  360. from proj.celery import app
  361. @app.task
  362. def log_error(request, exc, traceback):
  363. with open(os.path.join('/var/errors', request.id), 'a') as fh:
  364. print('--\n\n{0} {1} {2}'.format(
  365. task_id, exc, traceback), file=fh)
  366. To make it even easier to link tasks together there's
  367. a special signature called :class:`~celery.chain` that lets
  368. you chain tasks together:
  369. .. code-block:: pycon
  370. >>> from celery import chain
  371. >>> from proj.tasks import add, mul
  372. >>> # (4 + 4) * 8 * 10
  373. >>> res = chain(add.s(4, 4), mul.s(8), mul.s(10))
  374. proj.tasks.add(4, 4) | proj.tasks.mul(8) | proj.tasks.mul(10)
  375. Calling the chain will call the tasks in the current process
  376. and return the result of the last task in the chain:
  377. .. code-block:: pycon
  378. >>> res = chain(add.s(4, 4), mul.s(8), mul.s(10))()
  379. >>> res.get()
  380. 640
  381. It also sets ``parent`` attributes so that you can
  382. work your way up the chain to get intermediate results:
  383. .. code-block:: pycon
  384. >>> res.parent.get()
  385. 64
  386. >>> res.parent.parent.get()
  387. 8
  388. >>> res.parent.parent
  389. <AsyncResult: eeaad925-6778-4ad1-88c8-b2a63d017933>
  390. Chains can also be made using the ``|`` (pipe) operator:
  391. .. code-block:: pycon
  392. >>> (add.s(2, 2) | mul.s(8) | mul.s(10)).apply_async()
  393. Graphs
  394. ~~~~~~
  395. In addition you can work with the result graph as a
  396. :class:`~celery.utils.graph.DependencyGraph`:
  397. .. code-block:: pycon
  398. >>> res = chain(add.s(4, 4), mul.s(8), mul.s(10))()
  399. >>> res.parent.parent.graph
  400. 285fa253-fcf8-42ef-8b95-0078897e83e6(1)
  401. 463afec2-5ed4-4036-b22d-ba067ec64f52(0)
  402. 872c3995-6fa0-46ca-98c2-5a19155afcf0(2)
  403. 285fa253-fcf8-42ef-8b95-0078897e83e6(1)
  404. 463afec2-5ed4-4036-b22d-ba067ec64f52(0)
  405. You can even convert these graphs to *dot* format:
  406. .. code-block:: pycon
  407. >>> with open('graph.dot', 'w') as fh:
  408. ... res.parent.parent.graph.to_dot(fh)
  409. and create images:
  410. .. code-block:: console
  411. $ dot -Tpng graph.dot -o graph.png
  412. .. image:: ../images/result_graph.png
  413. .. _canvas-group:
  414. Groups
  415. ------
  416. .. versionadded:: 3.0
  417. A group can be used to execute several tasks in parallel.
  418. The :class:`~celery.group` function takes a list of signatures:
  419. .. code-block:: pycon
  420. >>> from celery import group
  421. >>> from proj.tasks import add
  422. >>> group(add.s(2, 2), add.s(4, 4))
  423. (proj.tasks.add(2, 2), proj.tasks.add(4, 4))
  424. If you **call** the group, the tasks will be applied
  425. one after another in the current process, and a :class:`~celery.result.GroupResult`
  426. instance is returned that can be used to keep track of the results,
  427. or tell how many tasks are ready and so on:
  428. .. code-block:: pycon
  429. >>> g = group(add.s(2, 2), add.s(4, 4))
  430. >>> res = g()
  431. >>> res.get()
  432. [4, 8]
  433. Group also supports iterators:
  434. .. code-block:: pycon
  435. >>> group(add.s(i, i) for i in xrange(100))()
  436. A group is a signature object, so it can be used in combination
  437. with other signatures.
  438. Group Results
  439. ~~~~~~~~~~~~~
  440. The group task returns a special result too,
  441. this result works just like normal task results, except
  442. that it works on the group as a whole:
  443. .. code-block:: pycon
  444. >>> from celery import group
  445. >>> from tasks import add
  446. >>> job = group([
  447. ... add.s(2, 2),
  448. ... add.s(4, 4),
  449. ... add.s(8, 8),
  450. ... add.s(16, 16),
  451. ... add.s(32, 32),
  452. ... ])
  453. >>> result = job.apply_async()
  454. >>> result.ready() # have all subtasks completed?
  455. True
  456. >>> result.successful() # were all subtasks successful?
  457. True
  458. >>> result.get()
  459. [4, 8, 16, 32, 64]
  460. The :class:`~celery.result.GroupResult` takes a list of
  461. :class:`~celery.result.AsyncResult` instances and operates on them as
  462. if it was a single task.
  463. It supports the following operations:
  464. * :meth:`~celery.result.GroupResult.successful`
  465. Return :const:`True` if all of the subtasks finished
  466. successfully (e.g., didn't raise an exception).
  467. * :meth:`~celery.result.GroupResult.failed`
  468. Return :const:`True` if any of the subtasks failed.
  469. * :meth:`~celery.result.GroupResult.waiting`
  470. Return :const:`True` if any of the subtasks
  471. isn't ready yet.
  472. * :meth:`~celery.result.GroupResult.ready`
  473. Return :const:`True` if all of the subtasks
  474. are ready.
  475. * :meth:`~celery.result.GroupResult.completed_count`
  476. Return the number of completed subtasks.
  477. * :meth:`~celery.result.GroupResult.revoke`
  478. Revoke all of the subtasks.
  479. * :meth:`~celery.result.GroupResult.join`
  480. Gather the results of all subtasks
  481. and return them in the same order as they were called (as a list).
  482. .. _canvas-chord:
  483. Chords
  484. ------
  485. .. versionadded:: 2.3
  486. .. note::
  487. Tasks used within a chord must *not* ignore their results. If the result
  488. backend is disabled for *any* task (header or body) in your chord you
  489. should read ":ref:`chord-important-notes`." Chords are not currently
  490. supported with the RPC result backend.
  491. A chord is a task that only executes after all of the tasks in a group have
  492. finished executing.
  493. Let's calculate the sum of the expression
  494. :math:`1 + 1 + 2 + 2 + 3 + 3 ... n + n` up to a hundred digits.
  495. First you need two tasks, :func:`add` and :func:`tsum` (:func:`sum` is
  496. already a standard function):
  497. .. code-block:: python
  498. @app.task
  499. def add(x, y):
  500. return x + y
  501. @app.task
  502. def tsum(numbers):
  503. return sum(numbers)
  504. Now you can use a chord to calculate each addition step in parallel, and then
  505. get the sum of the resulting numbers:
  506. .. code-block:: pycon
  507. >>> from celery import chord
  508. >>> from tasks import add, tsum
  509. >>> chord(add.s(i, i)
  510. ... for i in xrange(100))(tsum.s()).get()
  511. 9900
  512. This is obviously a very contrived example, the overhead of messaging and
  513. synchronization makes this a lot slower than its Python counterpart:
  514. .. code-block:: pycon
  515. >>> sum(i + i for i in xrange(100))
  516. The synchronization step is costly, so you should avoid using chords as much
  517. as possible. Still, the chord is a powerful primitive to have in your toolbox
  518. as synchronization is a required step for many parallel algorithms.
  519. Let's break the chord expression down:
  520. .. code-block:: pycon
  521. >>> callback = tsum.s()
  522. >>> header = [add.s(i, i) for i in range(100)]
  523. >>> result = chord(header)(callback)
  524. >>> result.get()
  525. 9900
  526. Remember, the callback can only be executed after all of the tasks in the
  527. header have returned. Each step in the header is executed as a task, in
  528. parallel, possibly on different nodes. The callback is then applied with
  529. the return value of each task in the header. The task id returned by
  530. :meth:`chord` is the id of the callback, so you can wait for it to complete
  531. and get the final return value (but remember to :ref:`never have a task wait
  532. for other tasks <task-synchronous-subtasks>`)
  533. .. _chord-errors:
  534. Error handling
  535. ~~~~~~~~~~~~~~
  536. So what happens if one of the tasks raises an exception?
  537. The chord callback result will transition to the failure state, and the error is set
  538. to the :exc:`~@ChordError` exception:
  539. .. code-block:: pycon
  540. >>> c = chord([add.s(4, 4), raising_task.s(), add.s(8, 8)])
  541. >>> result = c()
  542. >>> result.get()
  543. .. code-block:: pytb
  544. Traceback (most recent call last):
  545. File "<stdin>", line 1, in <module>
  546. File "*/celery/result.py", line 120, in get
  547. interval=interval)
  548. File "*/celery/backends/amqp.py", line 150, in wait_for
  549. raise meta['result']
  550. celery.exceptions.ChordError: Dependency 97de6f3f-ea67-4517-a21c-d867c61fcb47
  551. raised ValueError('something something',)
  552. While the traceback may be different depending on the result backend used,
  553. you can see that the error description includes the id of the task that failed
  554. and a string representation of the original exception. You can also
  555. find the original traceback in ``result.traceback``.
  556. Note that the rest of the tasks will still execute, so the third task
  557. (``add.s(8, 8)``) is still executed even though the middle task failed.
  558. Also the :exc:`~@ChordError` only shows the task that failed
  559. first (in time): it doesn't respect the ordering of the header group.
  560. To perform an action when a chord fails you can therefore attach
  561. an errback to the chord callback:
  562. .. code-block:: python
  563. @app.task
  564. def on_chord_error(request, exc, traceback):
  565. print('Task {0!r} raised error: {1!r}'.format(request.id, exc))
  566. .. code-block:: pycon
  567. >>> c = (group(add.s(i, i) for i in range(10)) |
  568. ... xsum.s().on_error(on_chord_error.s()))).delay()
  569. .. _chord-important-notes:
  570. Important Notes
  571. ~~~~~~~~~~~~~~~
  572. Tasks used within a chord must *not* ignore their results. In practice this
  573. means that you must enable a :const:`result_backend` in order to use
  574. chords. Additionally, if :const:`task_ignore_result` is set to :const:`True`
  575. in your configuration, be sure that the individual tasks to be used within
  576. the chord are defined with :const:`ignore_result=False`. This applies to both
  577. Task subclasses and decorated tasks.
  578. Example Task subclass:
  579. .. code-block:: python
  580. class MyTask(Task):
  581. ignore_result = False
  582. Example decorated task:
  583. .. code-block:: python
  584. @app.task(ignore_result=False)
  585. def another_task(project):
  586. do_something()
  587. By default the synchronization step is implemented by having a recurring task
  588. poll the completion of the group every second, calling the signature when
  589. ready.
  590. Example implementation:
  591. .. code-block:: python
  592. from celery import maybe_signature
  593. @app.task(bind=True)
  594. def unlock_chord(self, group, callback, interval=1, max_retries=None):
  595. if group.ready():
  596. return maybe_signature(callback).delay(group.join())
  597. raise self.retry(countdown=interval, max_retries=max_retries)
  598. This is used by all result backends except Redis and Memcached: they
  599. increment a counter after each task in the header, then applies the callback
  600. when the counter exceeds the number of tasks in the set.
  601. The Redis and Memcached approach is a much better solution, but not easily
  602. implemented in other backends (suggestions welcome!).
  603. .. note::
  604. Chords don't properly work with Redis before version 2.2; you'll need to
  605. upgrade to at least redis-server 2.2 to use them.
  606. .. note::
  607. If you're using chords with the Redis result backend and also overriding
  608. the :meth:`Task.after_return` method, you need to make sure to call the
  609. super method or else the chord callback won't be applied.
  610. .. code-block:: python
  611. def after_return(self, *args, **kwargs):
  612. do_something()
  613. super(MyTask, self).after_return(*args, **kwargs)
  614. .. _canvas-map:
  615. Map & Starmap
  616. -------------
  617. :class:`~celery.map` and :class:`~celery.starmap` are built-in tasks
  618. that calls the task for every element in a sequence.
  619. They differ from group in that
  620. - only one task message is sent
  621. - the operation is sequential.
  622. For example using ``map``:
  623. .. code-block:: pycon
  624. >>> from proj.tasks import add
  625. >>> ~xsum.map([range(10), range(100)])
  626. [45, 4950]
  627. is the same as having a task doing:
  628. .. code-block:: python
  629. @app.task
  630. def temp():
  631. return [xsum(range(10)), xsum(range(100))]
  632. and using ``starmap``:
  633. .. code-block:: pycon
  634. >>> ~add.starmap(zip(range(10), range(10)))
  635. [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
  636. is the same as having a task doing:
  637. .. code-block:: python
  638. @app.task
  639. def temp():
  640. return [add(i, i) for i in range(10)]
  641. Both ``map`` and ``starmap`` are signature objects, so they can be used as
  642. other signatures and combined in groups etc., for example
  643. to call the starmap after 10 seconds:
  644. .. code-block:: pycon
  645. >>> add.starmap(zip(range(10), range(10))).apply_async(countdown=10)
  646. .. _canvas-chunks:
  647. Chunks
  648. ------
  649. Chunking lets you divide an iterable of work into pieces, so that if
  650. you have one million objects, you can create 10 tasks with hundred
  651. thousand objects each.
  652. Some may worry that chunking your tasks results in a degradation
  653. of parallelism, but this is rarely true for a busy cluster
  654. and in practice since you're avoiding the overhead of messaging
  655. it may considerably increase performance.
  656. To create a chunks signature you can use :meth:`@Task.chunks`:
  657. .. code-block:: pycon
  658. >>> add.chunks(zip(range(100), range(100)), 10)
  659. As with :class:`~celery.group` the act of sending the messages for
  660. the chunks will happen in the current process when called:
  661. .. code-block:: pycon
  662. >>> from proj.tasks import add
  663. >>> res = add.chunks(zip(range(100), range(100)), 10)()
  664. >>> res.get()
  665. [[0, 2, 4, 6, 8, 10, 12, 14, 16, 18],
  666. [20, 22, 24, 26, 28, 30, 32, 34, 36, 38],
  667. [40, 42, 44, 46, 48, 50, 52, 54, 56, 58],
  668. [60, 62, 64, 66, 68, 70, 72, 74, 76, 78],
  669. [80, 82, 84, 86, 88, 90, 92, 94, 96, 98],
  670. [100, 102, 104, 106, 108, 110, 112, 114, 116, 118],
  671. [120, 122, 124, 126, 128, 130, 132, 134, 136, 138],
  672. [140, 142, 144, 146, 148, 150, 152, 154, 156, 158],
  673. [160, 162, 164, 166, 168, 170, 172, 174, 176, 178],
  674. [180, 182, 184, 186, 188, 190, 192, 194, 196, 198]]
  675. while calling ``.apply_async`` will create a dedicated
  676. task so that the individual tasks are applied in a worker
  677. instead:
  678. .. code-block:: pycon
  679. >>> add.chunks(zip(range(100), range(100)), 10).apply_async()
  680. You can also convert chunks to a group:
  681. .. code-block:: pycon
  682. >>> group = add.chunks(zip(range(100), range(100)), 10).group()
  683. and with the group skew the countdown of each task by increments
  684. of one:
  685. .. code-block:: pycon
  686. >>> group.skew(start=1, stop=10)()
  687. This means that the first task will have a countdown of one second, the second
  688. task a countdown of two seconds, and so on.