canvas.rst 23 KB

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