first-steps-with-celery.rst 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. .. _tut-celery:
  2. .. _first-steps:
  3. =========================
  4. First Steps with Celery
  5. =========================
  6. Celery is a task queue with batteries included.
  7. It's easy to use so that you can get started without learning
  8. the full complexities of the problem it solves. It's designed
  9. around best practices so that your product can scale
  10. and integrate with other languages, and it comes with the
  11. tools and support you need to run such a system in production.
  12. In this tutorial you'll learn the absolute basics of using Celery.
  13. Learn about;
  14. - Choosing and installing a message transport (broker).
  15. - Installing Celery and creating your first task.
  16. - Starting the worker and calling tasks.
  17. - Keeping track of tasks as they transition through different states,
  18. and inspecting return values.
  19. Celery may seem daunting at first - but don't worry - this tutorial
  20. will get you started in no time. It's deliberately kept simple, so
  21. as to not confuse you with advanced features.
  22. After you have finished this tutorial,
  23. it's a good idea to browse the rest of the documentation.
  24. For example the :ref:`next-steps` tutorial will
  25. showcase Celery's capabilities.
  26. .. contents::
  27. :local:
  28. .. _celerytut-broker:
  29. Choosing a Broker
  30. =================
  31. Celery requires a solution to send and receive messages; usually this
  32. comes in the form of a separate service called a *message broker*.
  33. There are several choices available, including:
  34. RabbitMQ
  35. --------
  36. `RabbitMQ`_ is feature-complete, stable, durable and easy to install.
  37. It's an excellent choice for a production environment.
  38. Detailed information about using RabbitMQ with Celery:
  39. :ref:`broker-rabbitmq`
  40. .. _`RabbitMQ`: http://www.rabbitmq.com/
  41. If you're using Ubuntu or Debian install RabbitMQ by executing this
  42. command:
  43. .. code-block:: console
  44. $ sudo apt-get install rabbitmq-server
  45. When the command completes, the broker will already be running in the background,
  46. ready to move messages for you: ``Starting rabbitmq-server: SUCCESS``.
  47. Don't worry if you're not running Ubuntu or Debian, you can go to this
  48. website to find similarly simple installation instructions for other
  49. platforms, including Microsoft Windows:
  50. http://www.rabbitmq.com/download.html
  51. Redis
  52. -----
  53. `Redis`_ is also feature-complete, but is more susceptible to data loss in
  54. the event of abrupt termination or power failures. Detailed information about using Redis:
  55. :ref:`broker-redis`
  56. .. _`Redis`: https://redis.io/
  57. Other brokers
  58. -------------
  59. In addition to the above, there are other experimental transport implementations
  60. to choose from, including :ref:`Amazon SQS <broker-sqs>`.
  61. See :ref:`broker-overview` for a full list.
  62. .. _celerytut-installation:
  63. Installing Celery
  64. =================
  65. Celery is on the Python Package Index (PyPI), so it can be installed
  66. with standard Python tools like ``pip`` or ``easy_install``:
  67. .. code-block:: console
  68. $ pip install celery
  69. Application
  70. ===========
  71. The first thing you need is a Celery instance. We call this the *Celery
  72. application* or just *app* for short. As this instance is used as
  73. the entry-point for everything you want to do in Celery, like creating tasks and
  74. managing workers, it must be possible for other modules to import it.
  75. In this tutorial we keep everything contained in a single module,
  76. but for larger projects you want to create
  77. a :ref:`dedicated module <project-layout>`.
  78. Let's create the file :file:`tasks.py`:
  79. .. code-block:: python
  80. from celery import Celery
  81. app = Celery('tasks', broker='pyamqp://guest@localhost//')
  82. @app.task
  83. def add(x, y):
  84. return x + y
  85. The first argument to :class:`~celery.app.Celery` is the name of the current module.
  86. This is only needed so that names can be automatically generated when the tasks are
  87. defined in the `__main__` module.
  88. The second argument is the broker keyword argument, specifying the URL of the
  89. message broker you want to use. Here using RabbitMQ (also the default option).
  90. See :ref:`celerytut-broker` above for more choices --
  91. for RabbitMQ you can use ``amqp://localhost``, or for Redis you can
  92. use ``redis://localhost``.
  93. You defined a single task, called ``add``, returning the sum of two numbers.
  94. .. _celerytut-running-the-worker:
  95. Running the Celery worker server
  96. ================================
  97. You can now run the worker by executing our program with the ``worker``
  98. argument:
  99. .. code-block:: console
  100. $ celery -A tasks worker --loglevel=info
  101. .. note::
  102. See the :ref:`celerytut-troubleshooting` section if the worker
  103. doesn't start.
  104. In production you'll want to run the worker in the
  105. background as a daemon. To do this you need to use the tools provided
  106. by your platform, or something like `supervisord`_ (see :ref:`daemonizing`
  107. for more information).
  108. For a complete listing of the command-line options available, do:
  109. .. code-block:: console
  110. $ celery worker --help
  111. There are also several other commands available, and help is also available:
  112. .. code-block:: console
  113. $ celery help
  114. .. _`supervisord`: http://supervisord.org
  115. .. _celerytut-calling:
  116. Calling the task
  117. ================
  118. To call our task you can use the :meth:`~@Task.delay` method.
  119. This is a handy shortcut to the :meth:`~@Task.apply_async`
  120. method that gives greater control of the task execution (see
  121. :ref:`guide-calling`)::
  122. >>> from tasks import add
  123. >>> add.delay(4, 4)
  124. The task has now been processed by the worker you started earlier.
  125. You can verify this by looking at the worker's console output.
  126. Calling a task returns an :class:`~@AsyncResult` instance.
  127. This can be used to check the state of the task, wait for the task to finish,
  128. or get its return value (or if the task failed, to get the exception and traceback).
  129. Results are not enabled by default. In order to do remote procedure calls
  130. or keep track of task results in a database, you will need to configure Celery to use a result
  131. backend. This is described in the next section.
  132. .. _celerytut-keeping-results:
  133. Keeping Results
  134. ===============
  135. If you want to keep track of the tasks' states, Celery needs to store or send
  136. the states somewhere. There are several
  137. built-in result backends to choose from: `SQLAlchemy`_/`Django`_ ORM,
  138. `Memcached`_, `Redis`_, :ref:`RPC <conf-rpc-result-backend>` (`RabbitMQ`_/AMQP),
  139. and -- or you can define your own.
  140. .. _`Memcached`: http://memcached.org
  141. .. _`MongoDB`: http://www.mongodb.org
  142. .. _`SQLAlchemy`: http://www.sqlalchemy.org/
  143. .. _`Django`: http://djangoproject.com
  144. For this example we use the `rpc` result backend, that sends states
  145. back as transient messages. The backend is specified via the ``backend`` argument to
  146. :class:`@Celery`, (or via the :setting:`result_backend` setting if
  147. you choose to use a configuration module):
  148. .. code-block:: python
  149. app = Celery('tasks', backend='rpc://', broker='pyamqp://')
  150. Or if you want to use Redis as the result backend, but still use RabbitMQ as
  151. the message broker (a popular combination):
  152. .. code-block:: python
  153. app = Celery('tasks', backend='redis://localhost', broker='pyamqp://')
  154. To read more about result backends please see :ref:`task-result-backends`.
  155. Now with the result backend configured, let's call the task again.
  156. This time you'll hold on to the :class:`~@AsyncResult` instance returned
  157. when you call a task:
  158. .. code-block:: pycon
  159. >>> result = add.delay(4, 4)
  160. The :meth:`~@AsyncResult.ready` method returns whether the task
  161. has finished processing or not:
  162. .. code-block:: pycon
  163. >>> result.ready()
  164. False
  165. You can wait for the result to complete, but this is rarely used
  166. since it turns the asynchronous call into a synchronous one:
  167. .. code-block:: pycon
  168. >>> result.get(timeout=1)
  169. 8
  170. In case the task raised an exception, :meth:`~@AsyncResult.get` will
  171. re-raise the exception, but you can override this by specifying
  172. the ``propagate`` argument:
  173. .. code-block:: pycon
  174. >>> result.get(propagate=False)
  175. If the task raised an exception, you can also gain access to the
  176. original traceback:
  177. .. code-block:: pycon
  178. >>> result.traceback
  179. .. warning::
  180. Backends use resources to store and transmit results. To ensure
  181. that resources are released, you must eventually call
  182. :meth:`~@AsyncResult.get` or :meth:`~@AsyncResult.forget` on
  183. EVERY :class:`~@AsyncResult` instance returned after calling
  184. a task.
  185. See :mod:`celery.result` for the complete result object reference.
  186. .. _celerytut-configuration:
  187. Configuration
  188. =============
  189. Celery, like a consumer appliance, doesn't need much configuration to operate.
  190. It has an input and an output. The input must be connected to a broker, and the output can
  191. be optionally connected to a result backend. However, if you look closely at the back,
  192. there's a lid revealing loads of sliders, dials, and buttons: this is the configuration.
  193. The default configuration should be good enough for most use cases, but there are
  194. many options that can be configured to make Celery work exactly as needed.
  195. Reading about the options available is a good idea to familiarize yourself with what
  196. can be configured. You can read about the options in the
  197. :ref:`configuration` reference.
  198. The configuration can be set on the app directly or by using a dedicated
  199. configuration module.
  200. As an example you can configure the default serializer used for serializing
  201. task payloads by changing the :setting:`task_serializer` setting:
  202. .. code-block:: python
  203. app.conf.task_serializer = 'json'
  204. If you're configuring many settings at once you can use ``update``:
  205. .. code-block:: python
  206. app.conf.update(
  207. task_serializer='json',
  208. accept_content=['json'], # Ignore other content
  209. result_serializer='json',
  210. timezone='Europe/Oslo',
  211. enable_utc=True,
  212. )
  213. For larger projects, a dedicated configuration module is recommended.
  214. Hard coding periodic task intervals and task routing options is discouraged.
  215. It is much better to keep these in a centralized location. This is especially
  216. true for libraries, as it enables users to control how their tasks behave.
  217. A centralized configuration will also allow your SysAdmin to make simple changes
  218. in the event of system trouble.
  219. You can tell your Celery instance to use a configuration module
  220. by calling the :meth:`@config_from_object` method:
  221. .. code-block:: python
  222. app.config_from_object('celeryconfig')
  223. This module is often called "``celeryconfig``", but you can use any
  224. module name.
  225. In the above case, a module named ``celeryconfig.py`` must be available to load from the
  226. current directory or on the Python path. It could look something like this:
  227. :file:`celeryconfig.py`:
  228. .. code-block:: python
  229. broker_url = 'pyamqp://'
  230. result_backend = 'rpc://'
  231. task_serializer = 'json'
  232. result_serializer = 'json'
  233. accept_content = ['json']
  234. timezone = 'Europe/Oslo'
  235. enable_utc = True
  236. To verify that your configuration file works properly and doesn't
  237. contain any syntax errors, you can try to import it:
  238. .. code-block:: console
  239. $ python -m celeryconfig
  240. For a complete reference of configuration options, see :ref:`configuration`.
  241. To demonstrate the power of configuration files, this is how you'd
  242. route a misbehaving task to a dedicated queue:
  243. :file:`celeryconfig.py`:
  244. .. code-block:: python
  245. task_routes = {
  246. 'tasks.add': 'low-priority',
  247. }
  248. Or instead of routing it you could rate limit the task
  249. instead, so that only 10 tasks of this type can be processed in a minute
  250. (10/m):
  251. :file:`celeryconfig.py`:
  252. .. code-block:: python
  253. task_annotations = {
  254. 'tasks.add': {'rate_limit': '10/m'}
  255. }
  256. If you're using RabbitMQ or Redis as the
  257. broker then you can also direct the workers to set a new rate limit
  258. for the task at runtime:
  259. .. code-block:: console
  260. $ celery -A tasks control rate_limit tasks.add 10/m
  261. worker@example.com: OK
  262. new rate limit set successfully
  263. See :ref:`guide-routing` to read more about task routing,
  264. and the :setting:`task_annotations` setting for more about annotations,
  265. or :ref:`guide-monitoring` for more about remote control commands
  266. and how to monitor what your workers are doing.
  267. Where to go from here
  268. =====================
  269. If you want to learn more you should continue to the
  270. :ref:`Next Steps <next-steps>` tutorial, and after that you
  271. can read the :ref:`User Guide <guide>`.
  272. .. _celerytut-troubleshooting:
  273. Troubleshooting
  274. ===============
  275. There's also a troubleshooting section in the :ref:`faq`.
  276. Worker doesn't start: Permission Error
  277. --------------------------------------
  278. - If you're using Debian, Ubuntu or other Debian-based distributions:
  279. Debian recently renamed the :file:`/dev/shm` special file
  280. to :file:`/run/shm`.
  281. A simple workaround is to create a symbolic link:
  282. .. code-block:: console
  283. # ln -s /run/shm /dev/shm
  284. - Others:
  285. If you provide any of the :option:`--pidfile <celery worker --pidfile>`,
  286. :option:`--logfile <celery worker --logfile>` or
  287. :option:`--statedb <celery worker --statedb>` arguments, then you must
  288. make sure that they point to a file or directory that's writable and
  289. readable by the user starting the worker.
  290. Result backend doesn't work or tasks are always in ``PENDING`` state
  291. --------------------------------------------------------------------
  292. All tasks are :state:`PENDING` by default, so the state would've been
  293. better named "unknown". Celery doesn't update the state when a task
  294. is sent, and any task with no history is assumed to be pending (you know
  295. the task id, after all).
  296. 1) Make sure that the task doesn't have ``ignore_result`` enabled.
  297. Enabling this option will force the worker to skip updating
  298. states.
  299. 2) Make sure the :setting:`task_ignore_result` setting isn't enabled.
  300. 3) Make sure that you don't have any old workers still running.
  301. It's easy to start multiple workers by accident, so make sure
  302. that the previous worker is properly shut down before you start a new one.
  303. An old worker that isn't configured with the expected result backend
  304. may be running and is hijacking the tasks.
  305. The :option:`--pidfile <celery worker --pidfile>` argument can be set to
  306. an absolute path to make sure this doesn't happen.
  307. 4) Make sure the client is configured with the right backend.
  308. If, for some reason, the client is configured to use a different backend
  309. than the worker, you won't be able to receive the result.
  310. Make sure the backend is configured correctly:
  311. .. code-block:: pycon
  312. >>> result = task.delay()
  313. >>> print(result.backend)