next-steps.rst 17 KB

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