next-steps.rst 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  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 v3.0 (Chiastic Slide)
  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. .. _app-argument:
  94. About the :option:`--app` argument
  95. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  96. The :option:`--app` argument specifies the Celery app instance to use,
  97. it must be in the form of ``module.path:celery``, where the part before the colon
  98. is the name of the module, and the attribute name comes last.
  99. If a package name is specified instead it will automatically
  100. try to find a ``celery`` module in that package, and if the name
  101. is a module it will try to find a ``celery`` attribute in that module.
  102. This means that these are all equal:
  103. $ celery --app=proj
  104. $ celery --app=proj.celery:
  105. $ celery --app=proj.celery:celery
  106. .. _calling-tasks:
  107. Calling Tasks
  108. =============
  109. You can call a task using the :meth:`delay` method::
  110. >>> add.delay(2, 2)
  111. This method is actually a star-argument shortcut to another method called
  112. :meth:`apply_async`::
  113. >>> add.apply_async((2, 2))
  114. The latter enables you to specify execution options like the time to run
  115. (countdown), the queue it should be sent to and so on::
  116. >>> add.apply_async((2, 2), queue='lopri', countdown=10)
  117. In the above example the task will be sent to a queue named ``lopri`` and the
  118. task will execute, at the earliest, 10 seconds after the message was sent.
  119. Applying the task directly will execute the task in the current process,
  120. so that no message is sent::
  121. >>> add(2, 2)
  122. 4
  123. These three methods - :meth:`delay`, :meth:`apply_async`, and applying
  124. (``__call__``), represents the Celery calling API, which are also used for
  125. subtasks.
  126. A more detailed overview of the Calling API can be found in the
  127. :ref:`Calling User Guide <guide-calling>`.
  128. Every task invocation will be given a unique identifier (an UUID), this
  129. is the task id.
  130. The ``delay`` and ``apply_async`` methods return an :class:`~@AsyncResult`
  131. instance, which can be used to keep track of the tasks execution state.
  132. But for this you need to enable a :ref:`result backend <task-result-backends>` so that
  133. the state can be stored somewhere.
  134. Results are disabled by default because of the fact that there is no result
  135. backend that suits every application, so to choose one you need to consider
  136. the drawbacks of each individual backend. For many tasks
  137. keeping the return value isn't even very useful, so it's a sensible default to
  138. have. Also note that result backends are not used for monitoring tasks and workers,
  139. for that we use dedicated event messages (see :ref:`guide-monitoring`).
  140. If you have a result backend configured we can retrieve the return
  141. value of a task::
  142. >>> res = add.delay(2, 2)
  143. >>> res.get(timeout=1)
  144. 4
  145. You can find the task's id by looking at the :attr:`id` attribute::
  146. >>> res.id
  147. d6b3aea2-fb9b-4ebc-8da4-848818db9114
  148. We can also inspect the exception and traceback if the task raised an
  149. exception, in fact ``result.get()`` will propagate any errors by default::
  150. >>> res = add.delay(2)
  151. >>> res.get(timeout=1)
  152. Traceback (most recent call last):
  153. File "<stdin>", line 1, in <module>
  154. File "/opt/devel/celery/celery/result.py", line 113, in get
  155. interval=interval)
  156. File "/opt/devel/celery/celery/backends/amqp.py", line 138, in wait_for
  157. raise self.exception_to_python(meta['result'])
  158. TypeError: add() takes exactly 2 arguments (1 given)
  159. If you don't wish for the errors to propagate then you can disable that
  160. by passing the ``propagate`` argument::
  161. >>> res.get(propagate=False)
  162. TypeError('add() takes exactly 2 arguments (1 given)',)
  163. In this case it will return the exception instance raised instead,
  164. and so to check whether the task succeeded or failed you will have to
  165. use the corresponding methods on the result instance::
  166. >>> res.failed()
  167. True
  168. >>> res.successful()
  169. False
  170. So how does it know if the task has failed or not? It can find out by looking
  171. at the tasks *state*::
  172. >>> res.state
  173. 'FAILURE'
  174. A task can only be in a single state, but it can progress through several
  175. states. The stages of a typical task can be::
  176. PENDING -> STARTED -> SUCCESS
  177. The started state is a special state that is only recorded if the
  178. :setting:`CELERY_TRACK_STARTED` setting is enabled, or if the
  179. ``@task(track_started=True)`` option is set for the task.
  180. The pending state is actually not a recorded state, but rather
  181. the default state for any task id that is unknown, which you can see
  182. from this example::
  183. >>> from proj.celery import celery
  184. >>> res = celery.AsyncResult('this-id-does-not-exist')
  185. >>> res.state
  186. 'PENDING'
  187. If the task is retried the stages can become even more complex,
  188. e.g, for a task that is retried two times the stages would be::
  189. PENDING -> STARTED -> RETRY -> STARTED -> RETRY -> STARTED -> SUCCESS
  190. To read more about task states you should see the :ref:`task-states` section
  191. in the tasks user guide.
  192. .. _designing-workflows:
  193. *Canvas*: Designing Workflows
  194. =============================
  195. We just learned how to call a task using the tasks ``delay`` method,
  196. and this is often all you need, but sometimes you may want to pass the
  197. signature of a task invocation to another process or as an argument to another
  198. function, for this Celery uses something called *subtasks*.
  199. A subtask wraps the arguments and execution options of a single task
  200. invocation in a way such that it can be passed to functions or even serialized
  201. and sent across the wire.
  202. You can create a subtask for the ``add`` task using the arguments ``(2, 2)``,
  203. and a countdown of 10 seconds like this::
  204. >>> add.subtask((2, 2), countdown=10)
  205. tasks.add(2, 2)
  206. There is also a shortcut using star arguments::
  207. >>> add.s(2, 2)
  208. tasks.add(2, 2)
  209. And there's that calling API again...
  210. -------------------------------------
  211. Subtask instances also supports the calling API, which means that they
  212. have the ``delay`` and ``apply_async`` methods.
  213. But there is a difference in that the subtask may already have
  214. an argument signature specified. The ``add`` task takes two arguments,
  215. so a subtask specifying two arguments would make a complete signature::
  216. >>> s1 = add.s(2, 2)
  217. >>> res = s2.delay()
  218. >>> res.get()
  219. 4
  220. But, you can also make incomplete signatures to create what we call
  221. *partials*::
  222. # incomplete partial: add(?, 2)
  223. >>> s2 = add.s(2)
  224. ``s2`` is now a partial subtask that needs another argument to be complete,
  225. and this can be resolved when calling the subtask::
  226. # resolves the partial: add(8, 2)
  227. >>> res = s2.delay(8)
  228. >>> res.get()
  229. 10
  230. Here we added the argument 8, which was prepended to the existing argument 2
  231. forming a complete signature of ``add(8, 2)``.
  232. Keyword arguments can also be added later, these are then merged with any
  233. existing keyword arguments, but with new arguments taking precedence::
  234. >>> s3 = add.s(2, 2, debug=True)
  235. >>> s3.delay(debug=False) # debug is now False.
  236. As stated subtasks supports the calling API, which means that:
  237. - ``subtask.apply_async(args=(), kwargs={}, **options)``
  238. Calls the subtask with optional partial arguments and partial
  239. keyword arguments. Also supports partial execution options.
  240. - ``subtask.delay(*args, **kwargs)``
  241. Star argument version of ``apply_async``. Any arguments will be prepended
  242. to the arguments in the signature, and keyword arguments is merged with any
  243. existing keys.
  244. So this all seems very useful, but what can we actually do with these?
  245. To get to that we must introduce the canvas primitives...
  246. The Primitives
  247. --------------
  248. .. topic:: overview of primitives
  249. .. hlist::
  250. :columns: 2
  251. - :ref:`group <canvas-group>`
  252. - :ref:`chain <canvas-chain>`
  253. - :ref:`chord <canvas-chord>`
  254. - :ref:`map <canvas-map>`
  255. - :ref:`starmap <canvas-map>`
  256. - :ref:`chunks <canvas-chunks>`
  257. The primitives are also subtasks themselves, so that they can be combined
  258. in any number of ways to compose complex workflows.
  259. Here's some examples::
  260. Be sure to read more about workflows in the :ref:`Canvas <guide-canvas>` user
  261. guide.
  262. **This document is incomplete - and ends here :(**