next-steps.rst 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. .. _next-steps:
  2. ============
  3. Next Steps
  4. ============
  5. The :ref:`first-steps` guide is intentionally minimal. In this guide
  6. we will demonstrate what Celery offers in more detail, including
  7. how to add Celery support for your application and library.
  8. .. contents::
  9. :local:
  10. Using Celery in your Application
  11. ================================
  12. .. _project-layout:
  13. Our Project
  14. -----------
  15. Project layout::
  16. proj/__init__.py
  17. /celery.py
  18. /tasks.py
  19. :file:`proj/celery.py`
  20. ~~~~~~~~~~~~~~~~~~~~~~
  21. .. literalinclude:: ../../examples/next-steps/proj/celery.py
  22. :language: python
  23. In this module we created our :class:`@Celery` instance (sometimes
  24. referred to as the *app*). To use Celery within your project
  25. you simply import this instance.
  26. - The ``broker`` argument specifies the URL of the broker to use.
  27. See :ref:`celerytut-broker` for more information.
  28. - The ``backend`` argument specifies the result backend to use,
  29. It's used to keep track of task state and results.
  30. While results are disabled by default we use the amqp backend here
  31. to demonstrate how retrieving the results work, you may want to use
  32. a different backend for your application, as they all have different
  33. strenghts and weaknesses. If you don't need results it's best
  34. to disable them. Results can also be disabled for individual tasks
  35. by setting the ``@task(ignore_result=True)`` option.
  36. See :ref:`celerytut-keeping-results` for more information.
  37. - The ``include`` argument is a list of modules to import when
  38. the worker starts. We need to add our tasks module here so
  39. that the worker is able to find our tasks.
  40. :file:`proj/tasks.py`
  41. ~~~~~~~~~~~~~~~~~~~~~
  42. .. literalinclude:: ../../examples/next-steps/proj/tasks.py
  43. :language: python
  44. Starting the worker
  45. -------------------
  46. The :program:`celery` program can be used to start the worker::
  47. $ celery worker --app=proj -l info
  48. When the worker starts you should see a banner and some messages::
  49. -------------- celery@halcyon.local v2.6.0rc4
  50. ---- **** -----
  51. --- * *** * -- [Configuration]
  52. -- * - **** --- . broker: amqp://guest@localhost:5672//
  53. - ** ---------- . app: __main__:0x1012d8590
  54. - ** ---------- . concurrency: 8 (processes)
  55. - ** ---------- . events: OFF (enable -E to monitor this worker)
  56. - ** ----------
  57. - *** --- * --- [Queues]
  58. -- ******* ---- . celery: exchange:celery(direct) binding:celery
  59. --- ***** -----
  60. [2012-06-08 16:23:51,078: WARNING/MainProcess] celery@halcyon.local has started.
  61. -- The *broker* is the URL you specifed in the broker argument in our ``celery``
  62. module, you can also specify a different broker on the command line by using
  63. the :option:`-b` option.
  64. -- *Concurrency* is the number of multiprocessing worker process used
  65. to process your tasks concurrently, when all of these are busy doing work
  66. new tasks will have to wait for one of the tasks to finish before
  67. it can be processed.
  68. The default concurrency number is the number of CPU's on that machine
  69. (including cores), you can specify a custom number using :option:`-c` option.
  70. There is no recommended value, as the optimal number depends on a number of
  71. factors, but if your tasks are mostly I/O-bound then you can try to increase
  72. it, experimentation has shown that adding more than twice the number
  73. of CPU's is rarely effective, and likely to degrade performance
  74. instead.
  75. Including the default multiprocessing pool, Celery also supports using
  76. Eventlet, Gevent, and threads (see :ref:`concurrency`).
  77. -- *Events* is an option that when enabled causes Celery to send
  78. monitoring messages (events) for actions occurring in the worker.
  79. These can be used by monitor programs like ``celery events``,
  80. celerymon and the Django-Celery admin monitor that you can read
  81. about in the :ref:`Monitoring and Management guide <guide-monitoring>`.
  82. -- *Queues* is the list of queues that the worker will consume
  83. tasks from. The worker can be told to consume from several queues
  84. at once, and this is used to route messages to specific workers
  85. as a means for Quality of Service, separation of concerns,
  86. and emulating priorities, all described in the :ref:`Routing Guide
  87. <guide-routing>`.
  88. You can get a complete list of command line arguments
  89. by passing in the `--help` flag::
  90. $ celery worker --help
  91. These options are described in more detailed in the :ref:`Workers Guide <guide-worker>`.
  92. .. sidebar:: About the :option:`--app` argument
  93. The :option:`--app` argument specifies the Celery app instance to use,
  94. it must be in the form of ``module.path:celery``, where the part before the colon
  95. is the name of the module, and the attribute name comes last.
  96. If a package name is specified instead it will automatically
  97. try to find a ``celery`` module in that package, and if the name
  98. is a module it will try to find a ``celery`` attribute in that module.
  99. This means that these are all equal:
  100. $ celery --app=proj
  101. $ celery --app=proj.celery:
  102. $ celery --app=proj.celery:celery
  103. .. _designing-work-flows:
  104. Designing Work-flows
  105. ====================
  106. A :func:`~celery.subtask` wraps the signature of a single task invocation:
  107. arguments, keyword arguments and execution options.
  108. A subtask for the ``add`` task can be created like this::
  109. >>> from celery import subtask
  110. >>> subtask(add.name, args=(4, 4))
  111. or you can create one from the task itself::
  112. >>> from proj.tasks import add
  113. >>> add.subtask(args=(4, 4))
  114. It takes the same arguments as the :meth:`~@Task.apply_async` method::
  115. >>> add.apply_async(args, kwargs, **options)
  116. >>> add.subtask(args, kwargs, **options)
  117. >>> add.apply_async((2, 2), countdown=1)
  118. >>> add.subtask((2, 2), countdown=1)
  119. And like there is a :meth:`~@Task.delay` shortcut for `apply_async`
  120. there is an :meth:`~@Task.s` shortcut for subtask::
  121. >>> add.s(*args, **kwargs)
  122. >>> add.s(2, 2)
  123. proj.tasks.add(2, 2)
  124. >>> add.s(2, 2) == add.subtask((2, 2))
  125. True
  126. You can't define options with :meth:`~@Task.s`, but a chaining
  127. ``set`` call takes care of that::
  128. >>> add.s(2, 2).set(countdown=1)
  129. proj.tasks.add(2, 2)
  130. Partials
  131. --------
  132. A subtask can be applied too::
  133. >>> add.s(2, 2).delay()
  134. >>> add.s(2, 2).apply_async(countdown=1)
  135. Specifying additional args, kwargs or options to ``apply_async``/``delay``
  136. creates partials:
  137. - Any arguments added will be prepended to the args in the signature::
  138. >>> partial = add.s(2) # incomplete signature
  139. >>> partial.delay(4) # 2 + 4
  140. >>> partial.apply_async((4, )) # same
  141. - Any keyword arguments added will be merged with the kwargs in the signature,
  142. with the new keyword arguments taking precedence::
  143. >>> s = add.s(2, 2)
  144. >>> s.delay(debug=True) # -> add(2, 2, debug=True)
  145. >>> s.apply_async(kwargs={"debug": True}) # same
  146. - Any options added will be merged with the options in the signature,
  147. with the new options taking precedence::
  148. >>> s = add.subtask((2, 2), countdown=10)
  149. >>> s.apply_async(countdown=1) # countdown is now 1
  150. You can also clone subtasks to augment these::
  151. >>> s = add.s(2)
  152. proj.tasks.add(2)
  153. >>> s.clone(args=(4, ), kwargs={"debug": True})
  154. proj.tasks.add(2, 4, debug=True)
  155. Partials are meant to be used with callbacks, any tasks linked or chord
  156. callbacks will be applied with the result of the parent task.
  157. Sometimes you want to specify a callback that does not take
  158. additional arguments, and in that case you can set the subtask
  159. to be immutable::
  160. >>> add.apply_async((2, 2), link=reset_buffers.subtask(immutable=True))
  161. The ``.si()`` shortcut can also be used to create immutable subtasks::
  162. >>> add.apply_async((2, 2), link=reset_buffers.si())
  163. Only the execution options can be set when a subtask is immutable,
  164. and it's not possible to apply the subtask with partial args/kwargs.
  165. .. note::
  166. In this tutorial we use the prefix operator `~` to subtasks.
  167. You probably shouldn't use it in your production code, but it's a handy shortcut
  168. when testing with the Python shell::
  169. >>> ~subtask
  170. >>> # is the same as
  171. >>> subtask.delay().get()
  172. Groups
  173. ------
  174. A group can be used to execute several tasks in parallel.
  175. The :class:`~celery.group` function takes a list of subtasks::
  176. >>> from celery import group
  177. >>> from proj.tasks import add
  178. >>> group(add.s(2, 2), add.s(4, 4))
  179. (proj.tasks.add(2, 2), proj.tasks.add(4, 4))
  180. If you **call** the group, the tasks will be applied
  181. one after one in the current process, and a :class:`~@TaskSetResult`
  182. instance is returned which can be used to keep track of the results,
  183. or tell how many tasks are ready and so on::
  184. >>> g = group(add.s(2, 2), add.s(4, 4))
  185. >>> res = g()
  186. >>> res.get()
  187. [4, 8]
  188. However, if you call ``apply_async`` on the group it will
  189. send a special grouping task, so that the action of applying
  190. the tasks happens in a worker instead of the current process::
  191. >>> res = g.apply_async()
  192. >>> res.get()
  193. [4, 8]
  194. Group also supports iterators::
  195. >>> group(add.s(i, i) for i in xrange(100))()
  196. A group is a subclass instance, so it can be used in combination
  197. with other subtasks.
  198. Map & Starmap
  199. -------------
  200. :class:`~celery.map` and :class:`~celery.starmap` are built-in tasks
  201. that calls the task for every element in a sequence.
  202. They differ from group in that
  203. - only one task message is sent
  204. - the operation is sequential.
  205. For example using ``map``:
  206. .. code-block:: python
  207. >>> from proj.tasks import add
  208. >>> ~xsum.map([range(10), range(100)])
  209. [45, 4950]
  210. is the same as having a task doing:
  211. .. code-block:: python
  212. @celery.task()
  213. def temp():
  214. return [xsum(range(10)), xsum(range(100))]
  215. and using ``starmap``::
  216. >>> ~add.starmap(zip(range(10), range(10)))
  217. [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
  218. is the same as having a task doing:
  219. .. code-block:: python
  220. @celery.task()
  221. def temp():
  222. return [add(i, i) for i in range(10)]
  223. Both ``map`` and ``starmap`` are subtasks, so they can be used as
  224. other subtasks and combined in groups etc., for example
  225. to apply the starmap after 10 seconds::
  226. >>> add.starmap(zip(range(10), range(10))).apply_async(countdown=10)
  227. Chunking
  228. --------
  229. -- Chunking lets you divide a iterable of work into pieces,
  230. so that if you have one million objects, you can create
  231. 10 tasks with hundred thousand objects each.
  232. Some may worry that chunking your tasks results in a degradation
  233. of parallelism, but this is rarely true for a busy cluster
  234. and in practice since you are avoiding the overhead of messaging
  235. it may considerably increase performance.
  236. To create a chunks subtask you can use :meth:`@Task.chunks`:
  237. .. code-block:: python
  238. >>> add.chunks(zip(range(100), range(100)), 10)
  239. As with :class:`~celery.group` the act of **calling**
  240. the chunks will apply the tasks in the current process:
  241. .. code-block:: python
  242. >>> from proj.tasks import add
  243. >>> res = add.chunks(zip(range(100), range(100)), 10)()
  244. >>> res.get()
  245. [[0, 2, 4, 6, 8, 10, 12, 14, 16, 18],
  246. [20, 22, 24, 26, 28, 30, 32, 34, 36, 38],
  247. [40, 42, 44, 46, 48, 50, 52, 54, 56, 58],
  248. [60, 62, 64, 66, 68, 70, 72, 74, 76, 78],
  249. [80, 82, 84, 86, 88, 90, 92, 94, 96, 98],
  250. [100, 102, 104, 106, 108, 110, 112, 114, 116, 118],
  251. [120, 122, 124, 126, 128, 130, 132, 134, 136, 138],
  252. [140, 142, 144, 146, 148, 150, 152, 154, 156, 158],
  253. [160, 162, 164, 166, 168, 170, 172, 174, 176, 178],
  254. [180, 182, 184, 186, 188, 190, 192, 194, 196, 198]]
  255. while calling ``.apply_async`` will create a dedicated
  256. task so that the individual tasks are applied in a worker
  257. instead::
  258. >>> add.chunks(zip(range(100), range(100), 10)).apply_async()
  259. You can also convert chunks to a group::
  260. >>> group = add.chunks(zip(range(100), range(100), 10)).group()
  261. and with the group skew the countdown of each task by increments
  262. of one::
  263. >>> group.skew(start=1, stop=10)()
  264. which means that the first task will have a countdown of 1, the second
  265. a countdown of 2 and so on.
  266. Chaining tasks
  267. --------------
  268. Tasks can be linked together, which in practice means adding
  269. a callback task::
  270. >>> res = add.apply_async((2, 2), link=mul.s(16))
  271. >>> res.get()
  272. 4
  273. The linked task will be applied with the result of its parent
  274. task as the first argument, which in the above case will result
  275. in ``mul(4, 16)`` since the result is 4.
  276. The results will keep track of what subtasks a task applies,
  277. and this can be accessed from the result instance::
  278. >>> res.children
  279. [<AsyncResult: 8c350acf-519d-4553-8a53-4ad3a5c5aeb4>]
  280. >>> res.children[0].get()
  281. 64
  282. The result instance also has a :meth:`~@AsyncResult.collect` method
  283. that treats the result as a graph, enabling you to iterate over
  284. the results::
  285. >>> list(res.collect())
  286. [(<AsyncResult: 7b720856-dc5f-4415-9134-5c89def5664e>, 4),
  287. (<AsyncResult: 8c350acf-519d-4553-8a53-4ad3a5c5aeb4>, 64)]
  288. By default :meth:`~@AsyncResult.collect` will raise an
  289. :exc:`~@IncompleteStream` exception if the graph is not fully
  290. formed (one of the tasks has not completed yet),
  291. but you can get an intermediate representation of the graph
  292. too::
  293. >>> for result, value in res.collect(intermediate=True)):
  294. ....
  295. You can link together as many tasks as you like,
  296. and subtasks can be linked too::
  297. >>> s = add.s(2, 2)
  298. >>> s.link(mul.s(4))
  299. >>> s.link(log_result.s())
  300. You can also add *error callbacks* using the ``link_error`` argument::
  301. >>> add.apply_async((2, 2), link_error=log_error.s())
  302. >>> add.subtask((2, 2), link_error=log_error.s())
  303. Since exceptions can only be serialized when pickle is used
  304. the error callbacks take the id of the parent task as argument instead:
  305. .. code-block:: python
  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("/var/errors/%s" % (task_id, )) as fh:
  312. fh.write("--\n\n%s %s %s" % (
  313. task_id, result.result, result.traceback))
  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)
  323. Calling the chain will apply 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 applying the chain happens
  330. in a worker::
  331. >>> res = chain(add.s(4, 4), mul.s(8), mul.s(10))
  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. $ dot -Tpng graph.dot -o graph.png
  361. .. image:: ../images/graph.png
  362. Chords
  363. ------