first-steps-with-celery.rst 14 KB

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