next-steps.rst 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  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. :depth: 1
  11. Using Celery in your Application
  12. ================================
  13. .. _project-layout:
  14. Our Project
  15. -----------
  16. Project layout::
  17. proj/__init__.py
  18. /celery.py
  19. /tasks.py
  20. :file:`proj/celery.py`
  21. ~~~~~~~~~~~~~~~~~~~~~~
  22. .. literalinclude:: ../../examples/next-steps/proj/celery.py
  23. :language: python
  24. In this module we created our :class:`@Celery` instance (sometimes
  25. referred to as the *app*). To use Celery within your project
  26. you simply import this instance.
  27. - The ``broker`` argument specifies the URL of the broker to use.
  28. See :ref:`celerytut-broker` for more information.
  29. - The ``backend`` argument specifies the result backend to use,
  30. It's used to keep track of task state and results.
  31. While results are disabled by default we use the amqp backend here
  32. to demonstrate how retrieving the results work, you may want to use
  33. a different backend for your application, as they all have different
  34. strenghts and weaknesses. If you don't need results it's best
  35. to disable them. Results can also be disabled for individual tasks
  36. by setting the ``@task(ignore_result=True)`` option.
  37. See :ref:`celerytut-keeping-results` for more information.
  38. - The ``include`` argument is a list of modules to import when
  39. the worker starts. We need to add our tasks module here so
  40. that the worker is able to find our tasks.
  41. :file:`proj/tasks.py`
  42. ~~~~~~~~~~~~~~~~~~~~~
  43. .. literalinclude:: ../../examples/next-steps/proj/tasks.py
  44. :language: python
  45. Starting the worker
  46. -------------------
  47. The :program:`celery` program can be used to start the worker::
  48. $ celery worker --app=proj -l info
  49. When the worker starts you should see a banner and some messages::
  50. -------------- celery@halcyon.local v2.6.0rc4
  51. ---- **** -----
  52. --- * *** * -- [Configuration]
  53. -- * - **** --- . broker: amqp://guest@localhost:5672//
  54. - ** ---------- . app: __main__:0x1012d8590
  55. - ** ---------- . concurrency: 8 (processes)
  56. - ** ---------- . events: OFF (enable -E to monitor this worker)
  57. - ** ----------
  58. - *** --- * --- [Queues]
  59. -- ******* ---- . celery: exchange:celery(direct) binding:celery
  60. --- ***** -----
  61. [2012-06-08 16:23:51,078: WARNING/MainProcess] celery@halcyon.local has started.
  62. -- The *broker* is the URL you specifed in the broker argument in our ``celery``
  63. module, you can also specify a different broker on the command line by using
  64. the :option:`-b` option.
  65. -- *Concurrency* is the number of multiprocessing worker process used
  66. to process your tasks concurrently, when all of these are busy doing work
  67. new tasks will have to wait for one of the tasks to finish before
  68. it can be processed.
  69. The default concurrency number is the number of CPU's on that machine
  70. (including cores), you can specify a custom number using :option:`-c` option.
  71. There is no recommended value, as the optimal number depends on a number of
  72. factors, but if your tasks are mostly I/O-bound then you can try to increase
  73. it, experimentation has shown that adding more than twice the number
  74. of CPU's is rarely effective, and likely to degrade performance
  75. instead.
  76. Including the default multiprocessing pool, Celery also supports using
  77. Eventlet, Gevent, and threads (see :ref:`concurrency`).
  78. -- *Events* is an option that when enabled causes Celery to send
  79. monitoring messages (events) for actions occurring in the worker.
  80. These can be used by monitor programs like ``celery events``,
  81. celerymon and the Django-Celery admin monitor that you can read
  82. about in the :ref:`Monitoring and Management guide <guide-monitoring>`.
  83. -- *Queues* is the list of queues that the worker will consume
  84. tasks from. The worker can be told to consume from several queues
  85. at once, and this is used to route messages to specific workers
  86. as a means for Quality of Service, separation of concerns,
  87. and emulating priorities, all described in the :ref:`Routing Guide
  88. <guide-routing>`.
  89. You can get a complete list of command line arguments
  90. by passing in the `--help` flag::
  91. $ celery worker --help
  92. These options are described in more detailed in the :ref:`Workers Guide <guide-workers>`.
  93. .. sidebar:: About the :option:`--app` argument
  94. The :option:`--app` argument specifies the Celery app instance to use,
  95. it must be in the form of ``module.path:celery``, where the part before the colon
  96. is the name of the module, and the attribute name comes last.
  97. If a package name is specified instead it will automatically
  98. try to find a ``celery`` module in that package, and if the name
  99. is a module it will try to find a ``celery`` attribute in that module.
  100. This means that these are all equal:
  101. $ celery --app=proj
  102. $ celery --app=proj.celery:
  103. $ celery --app=proj.celery:celery
  104. .. _calling-tasks:
  105. Calling Tasks
  106. =============
  107. You can call a task using the :meth:`delay` method::
  108. >>> add.delay(2, 2)
  109. This method is actually a star-argument shortcut to another method called
  110. :meth:`apply_async`::
  111. >>> add.apply_async((2, 2))
  112. The latter enables you to specify execution options like the time to run
  113. (countdown), the queue it should be sent to and so on::
  114. >>> add.apply_async((2, 2), queue='lopri', countdown=10)
  115. In the above example the task will be sent to a queue named ``lopri`` and the
  116. task will execute, at the earliest, 10 seconds after the message was sent.
  117. Applying the task directly will execute the task in the current process,
  118. so that no message is sent::
  119. >>> add(2, 2)
  120. 4
  121. These three methods - :meth:`delay`, :meth:`apply_async`, and applying
  122. (``__call__``), represents the Celery calling API, which are also used for
  123. subtasks.
  124. A more detailed overview of the Calling API can be found in the
  125. :ref:`Calling User Guide <guide-calling>`.
  126. Every task invocation will be given a unique identifier (an UUID), this
  127. is the task id.
  128. The ``delay`` and ``apply_async`` methods return an :class:`~@AsyncResult`
  129. instance, which can be used to keep track of the tasks execution state.
  130. But for this you need to enable a :ref:`result backend <task-result-backend>` so that
  131. the state can be stored somewhere.
  132. Results are disabled by default because of the fact that there is no result
  133. backend that suits every application, so to choose one you need to consider
  134. the drawbacks of each individual backend. For many tasks
  135. keeping the return value isn't even very useful, so it's a sensible default to
  136. have. Also note that result backends are not used for monitoring tasks and workers,
  137. for that we use dedicated event messages (see :ref:`guide-monitoring`).
  138. If you have a result backend configured we can retrieve the return
  139. value of a task::
  140. >>> res = add.delay(2, 2)
  141. >>> res.get(timeout=1)
  142. 4
  143. You can find the task's id by looking at the :attr:`id` attribute::
  144. >>> res.id
  145. d6b3aea2-fb9b-4ebc-8da4-848818db9114
  146. We can also inspect the exception and traceback if the task raised an
  147. exception, in fact ``result.get()`` will propagate any errors by default::
  148. >>> res = add.delay(2)
  149. >>> res.get(timeout=1)
  150. Traceback (most recent call last):
  151. File "<stdin>", line 1, in <module>
  152. File "/opt/devel/celery/celery/result.py", line 113, in get
  153. interval=interval)
  154. File "/opt/devel/celery/celery/backends/amqp.py", line 138, in wait_for
  155. raise self.exception_to_python(meta['result'])
  156. TypeError: add() takes exactly 2 arguments (1 given)
  157. If you don't wish for the errors to propagate then you can disable that
  158. by passing the ``propagate`` argument::
  159. >>> res.get(propagate=False)
  160. TypeError('add() takes exactly 2 arguments (1 given)',)
  161. In this case it will return the exception instance raised instead,
  162. and so to check whether the task succeeded or failed you will have to
  163. use the corresponding methods on the result instance::
  164. >>> res.failed()
  165. True
  166. >>> res.successful()
  167. False
  168. So how does it know if the task has failed or not? It can find out by looking
  169. at the tasks *state*::
  170. >>> res.state
  171. 'FAILURE'
  172. A task can only be in a single state, but it can progress through several
  173. states. The stages of a typical task can be::
  174. PENDING -> STARTED -> SUCCESS
  175. The started state is a special state that is only recorded if the
  176. :setting:`CELERY_TRACK_STARTED` setting is enabled, or if the
  177. ``@task(track_started=True)`` option is set for the task.
  178. The pending state is actually not a recorded state, but rather
  179. the default state for any task id that is unknown, which you can see
  180. from this example::
  181. >>> from proj.celery import celery
  182. >>> res = celery.AsyncResult('this-id-does-not-exist')
  183. >>> res.state
  184. 'PENDING'
  185. If the task is retried the stages can become even more complex,
  186. e.g, for a task that is retried two times the stages would be::
  187. PENDING -> STARTED -> RETRY -> STARTED -> RETRY -> STARTED -> SUCCESS
  188. To read more about task states you should see the :ref:`task-states` section
  189. in the tasks user guide.
  190. .. _designing-workflows:
  191. *Canvas*: Designing Workflows
  192. =============================
  193. We just learned how to call a task using the tasks ``delay`` method,
  194. and this is often all you need, but sometimes you may want to pass the
  195. signature of a task invocation to another process or as an argument to another
  196. function, for this Celery uses something called *subtasks*.
  197. A subtask wraps the arguments and execution options of a single task
  198. invocation in a way such that it can be passed to functions or even serialized
  199. and sent across the wire.
  200. You can create a subtask for the ``add`` task using the arguments ``(2, 2)``,
  201. and a countdown of 10 seconds like this::
  202. >>> add.subtask((2, 2), countdown=10)
  203. tasks.add(2, 2)
  204. There is also a shortcut using star arguments::
  205. >>> add.s(2, 2)
  206. tasks.add(2, 2)
  207. and it also supports keyword arguments::
  208. >>> add.s(2, 2, debug=True)
  209. tasks.add(2, 2, debug=True)
  210. From any subtask instance we can inspect the different fields::
  211. >>> s = add.subtask((2, 2), {'debug': True}, countdown=10)
  212. >>> s.args
  213. (2, 2)
  214. >>> s.kwargs
  215. {'debug': True}
  216. >>> s.options
  217. {'countdown': 10}
  218. And there's that calling API again...
  219. -------------------------------------
  220. Subtask instances also support the calling API, which means you can use
  221. ``delay``, ``apply_async``, or *calling* it directly.
  222. But there is a difference in that the subtask may already have
  223. an argument signature specified. The ``add`` task takes two arguments,
  224. so a subtask specifying two arguments would make a complete signature::
  225. >>> s1 = add.s(2, 2)
  226. >>> res = s2.delay()
  227. >>> res.get()
  228. 4
  229. But, you can also make incomplete signatures to create what we call
  230. *partials*::
  231. # incomplete partial: add(?, 2)
  232. >>> s2 = add.s(2)
  233. ``s2`` is now a partial subtask that needs another argument to be complete,
  234. and this can actually be resolved when calling the subtask::
  235. # resolves the partial: add(8, 2)
  236. >>> res = s2.delay(8)
  237. >>> res.get()
  238. 10
  239. Here we added the argument 8, which was prepended to the existing argument 2
  240. forming a complete signature of ``add(8, 2)``.
  241. Keyword arguments can also be added later, these are then merged with any
  242. existing keyword arguments, but with new arguments taking precedence::
  243. >>> s3 = add.s(2, 2, debug=True)
  244. >>> s3.delay(debug=False) # debug is now False.
  245. As stated subtasks supports the calling API, and with the introduction
  246. of partial arguments, which means that:
  247. - ``subtask.apply_async(args=(), kwargs={}, **options)``
  248. Calls the subtask with optional partial arguments and partial
  249. keyword arguments. Also supports partial execution options.
  250. - ``subtask.delay(*args, **kwargs)``
  251. Star argument version of ``apply_async``. Any arguments will be prepended
  252. to the arguments in the signature, and keyword arguments is merged with any
  253. existing keys.
  254. So this all seems very useful, but what can we actually do with these?
  255. To get to that we must introduce the canvas primitives...
  256. The Primitives
  257. --------------
  258. - ``group``
  259. The group primitive is a subtask that takes a list of tasks that should
  260. be applied in parallel.
  261. - ``chain``
  262. The chain primitive lets us link together subtasks so that one is called
  263. after the other, essentially forming a *chain* of callbacks.
  264. - ``chord``
  265. A chord is just like a group but with a callback. A group consists
  266. of a header group and a body, where the body is a task that should execute
  267. after all of the tasks in the header is complete.
  268. - ``map``
  269. The map primitive works like the built-in ``map`` function, but creates
  270. a temporary task where a list of arguments is applied to the task.
  271. E.g. ``task.map([1, 2])`` results in a single task
  272. being called, appyling the arguments in order to the task function so
  273. that the result is::
  274. res = [task(1), task(2)]
  275. - ``starmap``
  276. Works exactly like map except the arguments are applied as ``*args``.
  277. For example ``add.starmap([(2, 2), (4, 4)])`` results in a single
  278. task calling::
  279. res = [add(2, 2), add(4, 4)]
  280. - ``chunks``
  281. Chunking splits a long list of arguments into parts, e.g the operation::
  282. >>> add.chunks(zip(xrange(1000), xrange(1000), 10))
  283. will create 10 tasks that apply 100 items each.
  284. The primitives are also subtasks themselves, so that they can be combined
  285. in any number of ways to compose complex workflows.
  286. Here's some examples::
  287. - Simple chain
  288. Here's a simple chain, the first task executes passing its return value
  289. to the next task in the chain, and so on.
  290. .. code-block:: python
  291. # 2 + 2 + 4 + 8
  292. >>> res = chain(add.s(2, 2), add.s(4), add.s(8))()
  293. >>> res.get()
  294. 16
  295. This can also be written using pipes::
  296. >>> (add.s(2, 2) | add.s(4) | add.s(8))().get()
  297. 16
  298. - Immutable subtasks
  299. As we have learned signatures can be partial, so that arguments can be
  300. added to the existing arguments, but you may not always want that,
  301. for example if you don't want the result of the previous task in a chain.
  302. In that case you can mark the subtask as immutable, so that the arguments
  303. cannot be changed::
  304. >>> add.subtask((2, 2), immutable=True)
  305. There's also an ``.si`` shortcut for this::
  306. >>> add.si(2, 2)
  307. Now we can create a chain of independent tasks instead::
  308. >>> res = (add.si(2, 2), add.si(4, 4), add.s(8, 8))()
  309. >>> res.get()
  310. 16
  311. >>> res.parent.get()
  312. 8
  313. >>> res.parent.parent.get()
  314. 4
  315. - Simple group
  316. We can easily create a group of tasks to execute in parallel::
  317. >>> res = group(add.s(i, i) for i in xrange(10))()
  318. >>> res.get(timeout=1)
  319. [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
  320. - For primitives `.apply_async` is special...
  321. as it will create a temporary task to apply the tasks in,
  322. for example by *applying the group*::
  323. >>> g = group(add.s(i, i) for i in xrange(10))
  324. >>> g() # << applying
  325. the act of sending the messages for the tasks in the group
  326. will happen in the current process,
  327. but with ``.apply_async`` this happens in a temporary task
  328. instead::
  329. >>> g = group(add.s(i, i) for i in xrange(10))
  330. >>> g.apply_async()
  331. This is useful because we can e.g. specify a time for the
  332. messages in the group to be called::
  333. >>> g.apply_async(countdown=10)
  334. - Simple chord
  335. The chord primitive enables us to add callback to be called when
  336. all of the tasks in a group has finished executing, which is often
  337. required for algorithms that aren't embarrassingly parallel::
  338. >>> res = chord((add.s(i, i) for i in xrange(10)), xsum.s())()
  339. >>> res.get()
  340. 90
  341. The above example creates 10 task that all start in parallel,
  342. and when all of them is complete the return values is combined
  343. into a list and sent to the ``xsum`` task.
  344. The body of a chord can also be immutable, so that the return value
  345. of the group is not passed on to the callback::
  346. >>> chord((import_contact.s(c) for c in contacts),
  347. ... notify_complete.si(import_id)).apply_async()
  348. Note the use of ``.si`` above which creates an immutable subtask.
  349. - Blow your mind by combining
  350. Chains can be partial too::
  351. >>> c1 = (add.s(4) | mul.s(8))
  352. # (16 + 4) * 8
  353. >>> res = c1(16)
  354. >>> res.get()
  355. 160
  356. Which means that you can combine chains too::
  357. # ((4 + 16) * 2 + 4) * 8
  358. >>> c2 = (add.s(4, 16) | mul.s(2) | (add.s(4) | mul.s(8)))
  359. >>> c2
  360. tasks.add(16) | tasks.mul(2) | tasks.add(4) | tasks.mul(8)
  361. >>> res = c2()
  362. >>> res.get()
  363. 352
  364. Chaining a group together with another task will automatically
  365. upgrade it to be a chord::
  366. >>> c3 = (group(add.s(i, i) for i in xrange(10) | xsum.s()))
  367. >>> res = c3()
  368. >>> res.get()
  369. 90
  370. Groups and chords accepts partial arguments too, which in case
  371. the return value of the previous task is sent to all tasks in the group::
  372. >>> new_user_workflow = (create_user.s() | group(
  373. ... import_contacts.s(),
  374. ... send_welcome_email.s()))
  375. ... new_user_workflow.delay(username='artv',
  376. ... first='Art',
  377. ... last='Vandelay',
  378. ... email='art@vandelay.com')
  379. Be sure to read more about workflows in the :ref:`Canvas <guide-canvas>` user
  380. guide.