canvas.rst 27 KB

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