canvas.rst 24 KB

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