first-steps-with-celery.rst 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  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. The :meth:`~@AsyncResult.ready` method returns whether the task
  149. has finished processing or not::
  150. >>> result.ready()
  151. False
  152. We can wait for the result to complete, but this is rarely used
  153. since it turns the asynchronous call into a synchronous one::
  154. >>> result.get(timeout=1)
  155. 4
  156. In case the task raised an exception, :meth:`~@AsyncResult.get` will
  157. re-raise the exception, but you can override this by specyfing
  158. the ``propagate`` argument::
  159. >>> result.get(propagate=True)
  160. If the task raised an exception we can also gain access to the
  161. original traceback::
  162. >>> result.traceback
  163. ...
  164. See :mod:`celery.result` for the complete result object reference.
  165. .. _celerytut-configuration:
  166. Configuration
  167. =============
  168. Celery, like a consumer appliance doesn't need much to be operated.
  169. It has an input and an output, where you must connect the input to a broker and maybe
  170. the output to a result backend if so wanted. But if you look closely at the back
  171. there is a lid revealing lots of sliders, dials and buttons: this is the configuration.
  172. The default configuration should be good enough for most uses, but there
  173. are many things to tweak so that Celery works just the way you want it to.
  174. Reading about the options available is a good idea to get familiar with what
  175. can be configured, see the :ref:`configuration` reference.
  176. The configuration can be set on the app directly or by using a dedicated
  177. configuration module.
  178. As an example you can configure the default serializer used for serializing
  179. task payloads by changing the :setting:`CELERY_TASK_SERIALIZER` setting:
  180. .. code-block:: python
  181. celery.conf.CELERY_TASK_SERIALIZER = "json"
  182. If you are configuring many settings at once you can use ``update``:
  183. .. code-block:: python
  184. celery.conf.update(
  185. CELERY_TASK_SERIALIZER="json",
  186. CELERY_RESULT_SERIALIZER="json",
  187. CELERY_TIMEZONE="Europe/Oslo",
  188. CELERY_ENABLE_UTC=True,
  189. )
  190. For larger projects using a dedicated configuration module is useful,
  191. in fact you are discouraged from hard coding
  192. periodic task intervals and task routing options, as it is much
  193. better to keep this in a centralized location, and especially for libaries
  194. it makes it possible for users to control how they want your tasks to behave,
  195. you can also imagine your sysadmin making simple changes to the configuration
  196. in the event of system trobule.
  197. You can tell your Celery instance to use a configuration module,
  198. by calling the :meth:`~@Celery.config_from_object` method:
  199. .. code-block:: python
  200. celery.config_from_object("celeryconfig")
  201. This module is often called "``celeryconfig``", but you can use any
  202. module name.
  203. A module named ``celeryconfig.py`` must then be available to load from the
  204. current directory or on the Python path, it could look like this:
  205. :file:`celeryconfig.py`:
  206. .. code-block:: python
  207. BROKER_URL = "amqp://"
  208. CELERY_RESULT_BACKEND = "amqp://"
  209. CELERY_TASK_SERIALIZER = "json"
  210. CELERY_RESULT_SERIALIZER = "json"
  211. CELERY_TIMEZONE = "Europe/Oslo"
  212. CELERY_ENABLE_UTC = True
  213. To verify that your configuration file works properly, and does't
  214. contain any syntax errors, you can try to import it::
  215. $ python -m celeryconfig
  216. For a complete reference of configuration options, see :ref:`configuration`.
  217. To demonstrate the power of configuration files, this how you would
  218. route a misbehaving task to a dedicated queue:
  219. :file:`celeryconfig.py`:
  220. .. code-block:: python
  221. CELERY_ROUTES = {
  222. "tasks.add": "low-priority",
  223. }
  224. Or instead of routing it you could rate limit the task
  225. instead, so that only 10 tasks of this type can execute in a minute
  226. (10/m):
  227. :file:`celeryconfig.py`:
  228. .. code-block:: python
  229. CELERY_ANNOTATIONS = {
  230. "tasks.add": {"rate_limit": "10/m"}
  231. }
  232. If you are using RabbitMQ, Redis or MongoDB as the
  233. broker then you can also direct the workers to set a new rate limit
  234. for the task at runtime::
  235. $ python tasks.py rate_limit tasks.add 10/m
  236. worker.example.com: OK
  237. new rate limit set successfully
  238. See :ref:`guide-routing` to read more about task routing,
  239. and the :setting:`CELERY_ANNOTATIONS` setting for more about annotations,
  240. or :ref:`guide-monitoring` for more about remote control commands,
  241. and how to monitor what your workers are doing.
  242. Where to go from here
  243. =====================
  244. After this you should read the :ref:`guide`. Specifically
  245. :ref:`guide-tasks` and :ref:`guide-executing`.