canvas.rst 26 KB

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