first-steps-with-celery.rst 12 KB

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