next-steps.rst 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. ============
  2. Next Steps
  3. ============
  4. The :ref:`first-steps` guide is intentionally minimal. In this guide
  5. we will demonstrate what Celery offers in more detail, including
  6. how to add Celery support for your application and library.
  7. .. contents::
  8. :local:
  9. Our Project
  10. ===========
  11. Project layout::
  12. proj/__init__.py
  13. /celery.py
  14. /tasks.py
  15. :file:`proj/celery.py`
  16. ----------------------
  17. .. literalinclude:: ../../examples/next-steps/proj/celery.py
  18. :language: python
  19. In this module we created our :class:`@Celery` instance (sometimes
  20. referred to as the *app*). To use Celery within your project
  21. you simply import this instance.
  22. - The ``broker`` argument specifies the URL of the broker to use.
  23. See :ref:`celerytut-broker` for more information.
  24. - The ``backend`` argument specifies the result backend to use,
  25. It's used to keep track of task state and results.
  26. While results are disabled by default we use the amqp backend here
  27. to demonstrate how retrieving the results work, you may want to use
  28. a different backend for your application, as they all have different
  29. strenghts and weaknesses. If you don't need results it's best
  30. to disable them. Results can also be disabled for individual tasks
  31. by setting the ``@task(ignore_result=True)`` option.
  32. See :ref:`celerytut-keeping-results` for more information.
  33. - The ``include`` argument is a list of modules to import when
  34. the worker starts. We need to add our tasks module here so
  35. that the worker is able to find our tasks.
  36. :file:`proj/tasks.py`
  37. ---------------------
  38. .. literalinclude:: ../../examples/next-steps/proj/tasks.py
  39. :language: python
  40. Starting the worker
  41. ===================
  42. The :program:`celery` program can be used to start the worker::
  43. $ celery worker --app=proj -l info
  44. The :option:`--app` argument specifies the Celery app instance to use,
  45. it must be in the form of ``module.path:celery``, where the part before the colon
  46. is the name of the module, and the attribute name comes last.
  47. If a package name is specified instead it will automatically
  48. try to find a ``celery`` module in that package, and if the name
  49. is a module it will try to find a ``celery`` attribute in that module.
  50. This means that the following all results in the same::
  51. $ celery --app=proj
  52. $ celery --app=proj.celery:
  53. $ celery --app=proj.celery:celery
  54. Subtasks
  55. ========
  56. A :func:`~celery.subtask` wraps the signature of a single task invocation:
  57. arguments, keyword arguments and execution options.
  58. A subtask for the ``add`` task can be created like this::
  59. >>> from celery import subtask
  60. >>> subtask(add.name, args=(4, 4))
  61. or you can create one from the task itself::
  62. >>> from proj.tasks import add
  63. >>> add.subtask(args=(4, 4))
  64. It takes the same arguments as the :meth:`~@Task.apply_async` method::
  65. >>> add.apply_async(args, kwargs, **options)
  66. >>> add.subtask(args, kwargs, **options)
  67. >>> add.apply_async((2, 2), countdown=1)
  68. >>> add.subtask((2, 2), countdown=1)
  69. And like there is a :meth:`~@Task.delay` shortcut for `apply_async`
  70. there is an :meth:`~@Task.s` shortcut for subtask::
  71. >>> add.s(*args, **kwargs)
  72. >>> add.s(2, 2)
  73. proj.tasks.add(2, 2)
  74. >>> add.s(2, 2) == add.subtask((2, 2))
  75. True
  76. You can't define options with :meth:`~@Task.s`, but a chaining
  77. ``set`` call takes care of that::
  78. >>> add.s(2, 2).set(countdown=1)
  79. proj.tasks.add(2, 2)
  80. Partials
  81. --------
  82. A subtask can be applied too::
  83. >>> add.s(2, 2).delay()
  84. >>> add.s(2, 2).apply_async(countdown=1)
  85. Specifying additional args, kwargs or options to ``apply_async``/``delay``
  86. creates partials:
  87. - Any arguments added will be prepended to the args in the signature::
  88. >>> partial = add.s(2) # incomplete signature
  89. >>> partial.delay(4) # 2 + 4
  90. >>> partial.apply_async((4, )) # same
  91. - Any keyword arguments added will be merged with the kwargs in the signature,
  92. with the new keyword arguments taking precedence::
  93. >>> s = add.s(2, 2)
  94. >>> s.delay(debug=True) # -> add(2, 2, debug=True)
  95. >>> s.apply_async(kwargs={"debug": True}) # same
  96. - Any options added will be merged with the options in the signature,
  97. with the new options taking precedence::
  98. >>> s = add.subtask((2, 2), countdown=10)
  99. >>> s.apply_async(countdown=1) # countdown is now 1
  100. You can also clone subtasks to augment these::
  101. >>> s = add.s(2)
  102. proj.tasks.add(2)
  103. >>> s.clone(args=(4, ), kwargs={"debug": True})
  104. proj.tasks.add(2, 4, debug=True)
  105. Partials are meant to be used with callbacks, any tasks linked or chord
  106. callbacks will be applied with the result of the parent task.
  107. Sometimes you want to specify a callback that does not take
  108. additional arguments, and in that case you can set the subtask
  109. to be immutable::
  110. >>> add.s(2, 2).link( reset_buffers.subtask(immutable=True) )
  111. Only the execution options can be set when a subtask is immutable,
  112. and it's not possible to apply the subtask with partial args/kwargs.
  113. .. note::
  114. In this tutorial we use the prefix operator `~` to subtasks.
  115. You probably shouldn't use it in your production code, but it's a handy shortcut
  116. when testing with the Python shell::
  117. >>> ~subtask
  118. >>> # is the same as
  119. >>> subtask.delay().get()
  120. Groups
  121. ------
  122. A group can be used to execute several tasks in parallel.
  123. The :class:`~celery.group` function takes a list of subtasks::
  124. >>> from celery import group
  125. >>> from proj.tasks import add
  126. >>> group(add.s(2, 2), add.s(4, 4))
  127. (proj.tasks.add(2, 2), proj.tasks.add(4, 4))
  128. If you **call** the group, the tasks will be applied
  129. one after one in the current process, and a :class:`~@TaskSetResult`
  130. instance is returned which can be used to keep track of the results,
  131. or tell how many tasks are ready and so on::
  132. >>> g = group(add.s(2, 2), add.s(4, 4))
  133. >>> res = g()
  134. >>> res.get()
  135. [4, 8]
  136. However, if you call ``apply_async`` on the group it will
  137. send a special grouping task, so that the action of applying
  138. the tasks happens in a worker instead of the current process::
  139. >>> res = g.apply_async()
  140. >>> res.get()
  141. [4, 8]
  142. Group also supports iterators::
  143. >>> group(add.s(i, i) for i in xrange(100))()
  144. A group is a subclass instance, so it can be used in combination
  145. with other subtasks.
  146. Map & Starmap
  147. -------------
  148. :class:`~celery.map` and :class:`~celery.starmap` are built-in tasks
  149. that calls the task for every element in a sequence.
  150. They differ from group in that
  151. - only one task message is sent
  152. - the operation is sequential.
  153. For example using ``map``:
  154. .. code-block:: python
  155. >>> from proj.tasks import add
  156. >>> ~xsum.map([range(10), range(100)])
  157. [45, 4950]
  158. is the same as having a task doing:
  159. .. code-block:: python
  160. @celery.task
  161. def temp():
  162. return [xsum(range(10)), xsum(range(100))]
  163. and using ``starmap``::
  164. >>> ~add.starmap(zip(range(10), range(10)))
  165. [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
  166. is the same as having a task doing:
  167. .. code-block:: python
  168. @celery.task
  169. def temp():
  170. return [add(i, i) for i in range(10)]
  171. Both ``map`` and ``starmap`` are subtasks, so they can be used as
  172. other subtasks and combined in groups etc., for example
  173. to apply the starmap after 10 seconds::
  174. >>> add.starmap(zip(range(10), range(10))).apply_async(countdown=10)
  175. Chunking
  176. --------
  177. -- Chunking lets you divide a iterable of work into pieces,
  178. so that if you have one million objects, you can create
  179. 10 tasks with hundred thousand objects each.
  180. Some may worry that chunking your tasks results in a degradation
  181. of parallelism, but this is rarely true for a busy cluster
  182. and in practice since you are avoiding the overhead of messaging
  183. it may considerably increase performance.
  184. To create a chunks subtask you can use :meth:`@Task.chunks`:
  185. .. code-block:: python
  186. >>> add.chunks(zip(range(100), range(100)), 10)
  187. As with :class:`~celery.group` the act of **calling**
  188. the chunks will apply the tasks in the current process:
  189. .. code-block:: python
  190. >>> from proj.tasks import add
  191. >>> res = add.chunks(zip(range(100), range(100)), 10)()
  192. >>> res.get()
  193. [[0, 2, 4, 6, 8, 10, 12, 14, 16, 18],
  194. [20, 22, 24, 26, 28, 30, 32, 34, 36, 38],
  195. [40, 42, 44, 46, 48, 50, 52, 54, 56, 58],
  196. [60, 62, 64, 66, 68, 70, 72, 74, 76, 78],
  197. [80, 82, 84, 86, 88, 90, 92, 94, 96, 98],
  198. [100, 102, 104, 106, 108, 110, 112, 114, 116, 118],
  199. [120, 122, 124, 126, 128, 130, 132, 134, 136, 138],
  200. [140, 142, 144, 146, 148, 150, 152, 154, 156, 158],
  201. [160, 162, 164, 166, 168, 170, 172, 174, 176, 178],
  202. [180, 182, 184, 186, 188, 190, 192, 194, 196, 198]]
  203. while calling ``.apply_async`` will create a dedicated
  204. task so that the individual tasks are applied in a worker
  205. instead::
  206. >>> add.chunks(zip(range(100), range(100), 10)).apply_async()
  207. You can also convert chunks to a group::
  208. >>> group = add.chunks(zip(range(100), range(100), 10)).group()
  209. and with the group skew the countdown of each task by increments
  210. of one::
  211. >>> group.skew(start=1, stop=10)()
  212. which means that the first task will have a countdown of 1, the second
  213. a countdown of 2 and so on.
  214. Chaining tasks
  215. --------------
  216. Tasks can be linked together, which in practice means adding
  217. a callback task::
  218. >>> res = add.apply_async((2, 2), link=mul.s(16))
  219. >>> res.get()
  220. 4
  221. The linked task will be applied with the result of its parent
  222. task as the first argument, which in the above case will result
  223. in ``mul(4, 16)`` since the result is 4.
  224. The results will keep track of what subtasks a task applies,
  225. and this can be accessed from the result instance::
  226. >>> res.children
  227. [<AsyncResult: 8c350acf-519d-4553-8a53-4ad3a5c5aeb4>]
  228. >>> res.children[0].get()
  229. 64
  230. The result instance also has a :meth:`~@AsyncResult.collect` method
  231. that treats the result as a graph, enabling you to iterate over
  232. the results::
  233. >>> list(res.collect())
  234. [(<AsyncResult: 7b720856-dc5f-4415-9134-5c89def5664e>, 4),
  235. (<AsyncResult: 8c350acf-519d-4553-8a53-4ad3a5c5aeb4>, 64)]
  236. By default :meth:`~@AsyncResult.collect` will raise an
  237. :exc:`~@IncompleteStream` exception if the graph is not fully
  238. formed (one of the tasks has not completed yet),
  239. but you can get an intermediate representation of the graph
  240. too::
  241. >>> for result, value in res.collect(intermediate=True)):
  242. ....
  243. You can link together as many tasks as you like,
  244. and subtasks can be linked too::
  245. >>> s = add.s(2, 2)
  246. >>> s.link(mul.s(4))
  247. >>> s.link(log_result.s())
  248. You can also add *error callbacks* using the ``link_error`` argument::
  249. >>> add.apply_async((2, 2), link_error=log_error.s())
  250. >>> add.subtask((2, 2), link_error=log_error.s())
  251. Since exceptions can only be serialized when pickle is used
  252. the error callbacks take the id of the parent task as argument instead:
  253. .. code-block:: python
  254. from proj.celery import celery
  255. @celery.task
  256. def log_error(task_id):
  257. result = celery.AsyncResult(task_id)
  258. result.get(propagate=False) # make sure result written.
  259. with open("/var/errors/%s" % (task_id, )) as fh:
  260. fh.write("--\n\n%s %s %s" % (
  261. task_id, result.result, result.traceback))
  262. To make it even easier to link tasks together there is
  263. a special subtask called :class:`~celery.chain` that lets
  264. you chain tasks together:
  265. .. code-block:: python
  266. >>> from celery import chain
  267. >>> from proj.tasks import add, mul
  268. # (4 + 4) * 8 * 10
  269. >>> res = chain(add.s(4, 4), mul.s(8), mul.s(10))
  270. proj.tasks.add(4, 4) | proj.tasks.mul(8)
  271. Calling the chain will apply the tasks in the current process
  272. and return the result of the last task in the chain::
  273. >>> res = chain(add.s(4, 4), mul.s(8), mul.s(10))
  274. >>> res.get()
  275. 640
  276. And calling ``apply_async`` will create a dedicated
  277. task so that the act of applying the chain happens
  278. in a worker::
  279. >>> res = chain(add.s(4, 4), mul.s(8), mul.s(10))
  280. >>> res.get()
  281. 640
  282. It also sets ``parent`` attributes so that you can
  283. work your way up the chain to get intermediate results::
  284. >>> res.parent.get()
  285. 64
  286. >>> res.parent.parent.get()
  287. 8
  288. >>> res.parent.parent
  289. <AsyncResult: eeaad925-6778-4ad1-88c8-b2a63d017933>
  290. Chains can also be made using the ``|`` (pipe) operator::
  291. >>> (add.s(2, 2) | mul.s(8) | mul.s(10)).apply_async()
  292. Graphs
  293. ~~~~~~
  294. In addition you can work with the result graph as a
  295. :class:`~celery.datastructures.DependencyGraph`:
  296. .. code-block:: python
  297. >>> res = chain(add.s(4, 4), mul.s(8), mul.s(10))()
  298. >>> res.parent.parent.graph
  299. 285fa253-fcf8-42ef-8b95-0078897e83e6(1)
  300. 463afec2-5ed4-4036-b22d-ba067ec64f52(0)
  301. 872c3995-6fa0-46ca-98c2-5a19155afcf0(2)
  302. 285fa253-fcf8-42ef-8b95-0078897e83e6(1)
  303. 463afec2-5ed4-4036-b22d-ba067ec64f52(0)
  304. You can even convert these graphs to *dot* format::
  305. >>> with open("graph.dot", "w") as fh:
  306. ... res.parent.parent.graph.to_dot(fh)
  307. and create images::
  308. $ dot -Tpng graph.dot -o graph.png
  309. .. image:: ../images/graph.png
  310. Chords
  311. ------