first-steps-with-celery.rst 14 KB

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