first-steps-with-celery.rst 14 KB

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