first-steps-with-celery.rst 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  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 broker.
  15. - Installing Celery and creating your first task
  16. - Starting the worker and executing tasks.
  17. - Keeping track of tasks as they execute, and inspecting return values.
  18. Celery may seem daunting at first - but don't worry - this tutorial
  19. will get you started in no time. It is deliberately kept simple, so
  20. to not confuse you with advances features.
  21. After you have finished this tutorial
  22. it's a good idea to browse the rest of the documentation,
  23. for example the :ref:`next-steps` tutorial, which will
  24. showcase Celery's capabilities.
  25. .. contents::
  26. :local:
  27. .. _celerytut-broker:
  28. Choosing a Broker
  29. =================
  30. Celery requires a solution to send and receive messages, usually this
  31. comes in the form of a separate service called a *message broker*.
  32. There are several choices available, including:
  33. * :ref:`broker-rabbitmq`
  34. `RabbitMQ`_ is feature-complete, stable, durable and easy to install.
  35. If you are using Ubuntu or Debian you can install RabbitMQ by executing this
  36. command::
  37. $ sudo apt-get install rabbitmq-server
  38. When the command completes the broker is already running in the background,
  39. ready to move messages for you.
  40. And don't worry if you're not running Ubuntu or Debian,
  41. you can go to this website to find similarly simple installation instructions
  42. for other platforms, including Microsoft Windows:
  43. http://www.rabbitmq.com/download.html
  44. * :ref:`broker-redis`
  45. `Redis`_ is also feature-complete, but is more susceptible to data loss in
  46. the event of abrupt termination or power failures.
  47. * :ref:`broker-sqlalchemy`
  48. * :ref:`broker-django`
  49. Using a database as a message queue is not recommended, but can be sufficient
  50. for very small installations. Celery can use the SQLAlchemy and Django ORM.
  51. * and more.
  52. In addition to the above, there are several other transport implementations
  53. to choose from, including :ref:`broker-mongodb`, :ref:`broker-django`,
  54. :ref:`broker-sqlalchemy`, and SQS.
  55. .. _`RabbitMQ`: http://www.rabbitmq.com/
  56. .. _`Redis`: http://redis.io/
  57. .. _`Transport Comparison`: http://kombu.rtfd.org/transport-comparison
  58. .. _celerytut-installation:
  59. Installing Celery
  60. =================
  61. Celery is on the Python Package Index (PyPI), so it can be installed
  62. with standard Python tools like ``pip`` or ``easy_install``::
  63. $ pip install celery
  64. Application
  65. ===========
  66. The first thing you need is a Celery instance, this is called the celery
  67. application or just app in short. Since this instance is used as
  68. the entry-point for everything you want to do in Celery, like creating tasks and
  69. managing workers, it must be possible for other modules to import it.
  70. In this tutorial we will keep everything contained in a single module,
  71. but for larger projects you probably want to create
  72. a :ref:`dedicated module <project-layout>`.
  73. Let's create the file :file:`tasks.py`:
  74. .. code-block:: python
  75. from celery import Celery
  76. celery = Celery("tasks", broker="amqp://guest@localhost//")
  77. @celery.task
  78. def add(x, y):
  79. return x + y
  80. if __name__ == "__main__":
  81. celery.start()
  82. The first argument to :class:`~celery.app.Celery` is the name of the current module,
  83. this is needed so that names can be automatically generated, the second
  84. argument is the broker keyword argument which specifies the URL of the
  85. message broker we want to use.
  86. The broker argument specifies the URL of the broker we want to use,
  87. we use RabbitMQ here, which is already the default option,
  88. but see :ref:`celerytut-broker` above if you want to use something different,
  89. e.g. for Redis you can use ``redis://localhost``, or MongoDB:
  90. ``mongodb://localhost``.
  91. We defined a single task, called ``add``, which returns the sum of two numbers.
  92. .. _celerytut-running-celeryd:
  93. Running the celery worker server
  94. ================================
  95. We can now run the worker by executing our program with the ``worker``
  96. argument::
  97. $ python tasks.py worker --loglevel=info
  98. In production you will probably want to run the worker in the
  99. background as a daemon. To do this you need to use the tools provided
  100. by your platform, or something like `supervisord`_ (see :ref:`daemonizing`
  101. for more information).
  102. For a complete listing of the command line options available, do::
  103. $ python tasks.py worker --help
  104. There also several other commands available, and help is also available::
  105. $ python tasks.py --help
  106. .. _`supervisord`: http://supervisord.org
  107. .. _celerytut-executing-task:
  108. Executing the task
  109. ==================
  110. Whenever we want to execute our task, we use the
  111. :meth:`~@Task.delay` method of the task.
  112. This is a handy shortcut to the :meth:`~@Task.apply_async`
  113. method which gives greater control of the task execution (see
  114. :ref:`guide-executing`)::
  115. >>> from tasks import add
  116. >>> add.delay(4, 4)
  117. The task should now be executed by the worker you started earlier,
  118. and you can verify that by looking at the workers console output.
  119. Applying a task returns an :class:`~@AsyncResult` instance,
  120. which can be used to check the state of the task, wait for the task to finish
  121. or get its return value (or if the task failed, the exception and traceback).
  122. But this isn't enabled by default, and you have to configure Celery to
  123. use a result backend, which is detailed in the next section.
  124. .. _celerytut-keeping-results:
  125. Keeping Results
  126. ---------------
  127. If you want to keep track of the tasks state, Celery needs to store or send
  128. the states somewhere. There are several
  129. built-in result backends to choose from: `SQLAlchemy`_/`Django`_ ORM,
  130. `Memcached`_, `Redis`_, AMQP (`RabbitMQ`_), and `MongoDB`_ -- or you can define your own.
  131. .. _`Memcached`: http://memcached.org
  132. .. _`MongoDB`: http://www.mongodb.org
  133. .. _`SQLAlchemy`: http://www.sqlalchemy.org/
  134. .. _`Django`: http://djangoproject.com
  135. For this example we will use the `amqp` result backend, which sends states
  136. as messages. The backend is specified via the ``backend`` argument to
  137. :class:`@Celery`, (or via the :setting:`CELERY_RESULT_BACKEND` setting if
  138. you choose to use a configuration module)::
  139. celery = Celery("tasks", backend="amqp", broker="amqp://")
  140. or if you want to use Redis as the result backend, but still use RabbitMQ as
  141. the message broker (a popular combination)::
  142. celery = Celery("tasks", backend="redis://localhost", broker="amqp://")
  143. To read more about result backends please see :ref:`task-result-backends`.
  144. Now with the result backend configured, let's execute the task again.
  145. This time we'll hold on to the :class:`~@AsyncResult` instance returned
  146. when you apply a task::
  147. >>> result = add.delay(4, 4)
  148. Here's some examples of what you can do with the result instance::
  149. >>> result.ready() # returns True if the task has finished processing.
  150. False
  151. >>> result.result # task is not ready, so no return value yet.
  152. None
  153. >>> result.get() # waits for the task and returns its retval.
  154. 8
  155. >>> result.result # direct access to result, doesn't re-raise errors.
  156. 8
  157. >>> result.successful() # returns True if the task didn't end in failure.
  158. True
  159. If the task raises an exception, the return value of
  160. :meth:`~@AsyncResult.failed` will be :const:`True`, and `result.result` will
  161. contain the exception instance raised by the task, and `result.traceback`
  162. will contain the original traceback as a string.
  163. .. _celerytut-configuration:
  164. Configuration
  165. -------------
  166. Celery, like a consumer appliance doesn't need much to be operated.
  167. It has an input and an output, where you must connect the input to a broker and maybe
  168. the output to a result backend if so wanted. But if you look closely at the back
  169. there is a lid revealing lots of sliders, dials and buttons: this is the configuration.
  170. The default configuration should be good enough for most uses, but there
  171. are many things to tweak so that Celery works just the way you want it to.
  172. Reading about the options available is a good idea to get familiar with what
  173. can be configured, see the :ref:`configuration` reference.
  174. The configuration can be set on the app directly or by using a dedicated
  175. configuration module.
  176. As an example you can configure the default serializer used for serializing
  177. task payloads by changing the :setting:`CELERY_TASK_SERIALIZER` setting:
  178. .. code-block:: python
  179. celery.conf.CELERY_TASK_SERIALIZER = "json"
  180. If you are configuring many settings at once you can use ``update``:
  181. .. code-block:: python
  182. celery.conf.update(
  183. CELERY_TASK_SERIALIZER="json",
  184. CELERY_RESULT_SERIALIZER="json",
  185. CELERY_TIMEZONE="Europe/Oslo",
  186. CELERY_ENABLE_UTC=True,
  187. )
  188. For larger projects using a dedicated configuration module is useful,
  189. in fact you are discouraged from hard coding
  190. periodic task intervals and task routing options, as it is much
  191. better to keep this in a centralized location, and especially for libaries
  192. it makes it possible for users to control how they want your tasks to behave,
  193. you can also imagine your sysadmin making simple changes to the configuration
  194. in the event of system trobule.
  195. You can tell your Celery instance to use a configuration module,
  196. often called ``celeryconfig.py``, with :meth:`config_from_obj` method:
  197. .. code-block:: python
  198. celery.config_from_object("celeryconfig")
  199. A module named ``celeryconfig.py`` must then be available to load from the
  200. current directory or on the Python path, it could look like this:
  201. :file:`celeryconfig.py`:
  202. .. code-block:: python
  203. BROKER_URL = "amqp://"
  204. CELERY_RESULT_BACKEND = "amqp://"
  205. CELERY_TASK_SERIALIZER = "json"
  206. CELERY_RESULT_SERIALIZER = "json"
  207. CELERY_TIMEZONE = "Europe/Oslo"
  208. CELERY_ENABLE_UTC = True
  209. To verify that your configuration file works properly, and does't
  210. contain any syntax errors, you can try to import it::
  211. $ python -m celeryconfig
  212. For a complete reference of configuration options, see :ref:`configuration`.
  213. To demonstrate the power of configuration files, this how you would
  214. route a misbehaving task to a dedicated queue:
  215. :file:`celeryconfig.py`:
  216. .. code-block:: python
  217. CELERY_ROUTES = {
  218. "tasks.add": "low-priority",
  219. }
  220. Or instead of routing it you could rate limit the task
  221. instead, so that only 10 tasks of this type can execute in a minute
  222. (10/m):
  223. :file:`celeryconfig.py`:
  224. .. code-block:: python
  225. CELERY_ANNOTATIONS = {
  226. "tasks.add": {"rate_limit": "10/m"}
  227. }
  228. If you are using RabbitMQ, Redis or MongoDB as the
  229. broker then you can also direct the workers to set new rate limit
  230. for the task at runtime::
  231. $ python tasks.py rate_limit tasks.add 10/m
  232. worker.example.com: OK
  233. new rate limit set successfully
  234. See :ref:`guide-routing` to read more about task routing,
  235. and the :setting:`CELERY_ANNOTATIONS` setting for more about annotations,
  236. or :ref:`guide-monitoring` for more about remote control commands,
  237. and how to monitor what your workers are doing.
  238. Where to go from here
  239. =====================
  240. After this you should read the :ref:`guide`. Specifically
  241. :ref:`guide-tasks` and :ref:`guide-executing`.