first-steps-with-celery.rst 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. .. _tut-celery:
  2. ========================
  3. First steps with Celery
  4. ========================
  5. .. contents::
  6. :local:
  7. .. _celerytut-broker:
  8. Choosing your Broker
  9. ====================
  10. Before you can use Celery you need to choose, install and run a broker.
  11. The broker is the service responsible for receiving and delivering task
  12. messages.
  13. There are several choices available, including:
  14. * `RabbitMQ`_
  15. Feature-complete, safe and durable. If not losing tasks
  16. is important to you, then this is your best option.
  17. See :ref:`broker-installation` for more about installing and configuring
  18. RabbitMQ.
  19. * `Redis`_
  20. Also feature-complete, but power failures or abrubt termination
  21. may result in data loss.
  22. See :ref:`otherqueues-redis` for configuration details.
  23. * Databases
  24. Using a database as a message queue is not recommended, but can be sufficient
  25. for very small installations. Celery can use the SQLAlchemy and Django ORMS.
  26. See :ref:`otherqueues-sqlalchemy` or :ref:`otherqueues-django`.
  27. * and more.
  28. In addition to the above, there are several other transport implementations
  29. to choose from, including CouchDB, Beanstalk, MongoDB, and SQS. See the Kombu
  30. documentation for more information.
  31. .. _`RabbitMQ`: http://www.rabbitmq.com/
  32. .. _`Redis`: http://redis.io/
  33. .. _celerytut-simple-tasks:
  34. Creating a simple task
  35. ======================
  36. In this tutorial we are creating a simple task that adds two
  37. numbers. Tasks are defined in normal Python modules.
  38. By convention we will call our module :file:`tasks.py`, and it looks
  39. like this:
  40. :file: `tasks.py`
  41. .. code-block:: python
  42. from celery.task import task
  43. @task
  44. def add(x, y):
  45. return x + y
  46. Behind the scenes the `@task` decorator actually creates a class that
  47. inherits from :class:`~celery.task.base.Task`. The best practice is to
  48. only create custom task classes when you want to change generic behavior,
  49. and use the decorator to define tasks.
  50. .. seealso::
  51. The full documentation on how to create tasks and task classes is in the
  52. :doc:`../userguide/tasks` part of the user guide.
  53. .. _celerytut-conf:
  54. Configuration
  55. =============
  56. Celery is configured by using a configuration module. By default
  57. this module is called :file:`celeryconfig.py`.
  58. The configuration module must either be in the current directory
  59. or on the Python path, so that it can be imported.
  60. You can also set a custom name for the configuration module by using
  61. the :envvar:`CELERY_CONFIG_MODULE` environment variable.
  62. Let's create our :file:`celeryconfig.py`.
  63. 1. Configure how we communicate with the broker (RabbitMQ in this example)::
  64. BROKER_URL = "amqp://guest:guest@localhost:5672//"
  65. 2. Define the backend used to store task metadata and return values::
  66. CELERY_RESULT_BACKEND = "amqp"
  67. The AMQP backend is non-persistent by default, and you can only
  68. fetch the result of a task once (as it's sent as a message).
  69. For list of backends available and related options see
  70. :ref:`conf-result-backend`.
  71. 3. Finally we list the modules the worker should import. This includes
  72. the modules containing your tasks.
  73. We only have a single task module, :file:`tasks.py`, which we added earlier::
  74. CELERY_IMPORTS = ("tasks", )
  75. That's it.
  76. There are more options available, like how many processes you want to
  77. use to process work in parallel (the :setting:`CELERY_CONCURRENCY` setting),
  78. and we could use a persistent result store backend, but for now, this should
  79. do. For all of the options available, see :ref:`configuration`.
  80. .. note::
  81. You can also specify modules to import using the :option:`-I` option to
  82. :mod:`~celery.bin.celeryd`::
  83. $ celeryd -l info -I tasks,handlers
  84. This can be a single, or a comma separated list of task modules to import
  85. when :program:`celeryd` starts.
  86. .. _celerytut-running-celeryd:
  87. Running the celery worker server
  88. ================================
  89. To test we will run the worker server in the foreground, so we can
  90. see what's going on in the terminal::
  91. $ celeryd --loglevel=INFO
  92. In production you will probably want to run the worker in the
  93. background as a daemon. To do this you need to use the tools provided
  94. by your platform, or something like `supervisord`_ (see :ref:`daemonizing`
  95. for more information).
  96. For a complete listing of the command line options available, do::
  97. $ celeryd --help
  98. .. _`supervisord`: http://supervisord.org
  99. .. _celerytut-executing-task:
  100. Executing the task
  101. ==================
  102. Whenever we want to execute our task, we use the
  103. :meth:`~celery.task.base.Task.delay` method of the task class.
  104. This is a handy shortcut to the :meth:`~celery.task.base.Task.apply_async`
  105. method which gives greater control of the task execution (see
  106. :ref:`guide-executing`).
  107. >>> from tasks import add
  108. >>> add.delay(4, 4)
  109. <AsyncResult: 889143a6-39a2-4e52-837b-d80d33efb22d>
  110. At this point, the task has been sent to the message broker. The message
  111. broker will hold on to the task until a worker server has consumed and
  112. executed it.
  113. Right now we have to check the worker log files to know what happened
  114. with the task. Applying a task returns an
  115. :class:`~celery.result.AsyncResult`, if you have configured a result store
  116. the :class:`~celery.result.AsyncResult` enables you to check the state of
  117. the task, wait for the task to finish, get its return value
  118. or exception/traceback if the task failed, and more.
  119. Keeping Results
  120. ---------------
  121. If you want to keep track of the tasks state, Celery needs to store or send
  122. the states somewhere. There are several
  123. built-in backends to choose from: SQLAlchemy/Django ORM, Memcached, Redis,
  124. AMQP, MongoDB, Tokyo Tyrant and Redis -- or you can define your own.
  125. For this example we will use the `amqp` result backend, which sends states
  126. as messages. The backend is configured via the ``CELERY_RESULT_BACKEND``
  127. option, in addition individual result backends may have additional settings
  128. you can configure::
  129. CELERY_RESULT_BACKEND = "amqp"
  130. #: We want the results to expire in 5 minutes, note that this requires
  131. #: RabbitMQ version 2.1.1 or higher, so please comment out if you have
  132. #: an earlier version.
  133. CELERY_TASK_RESULT_EXPIRES = 300
  134. To read more about result backends please see :ref:`task-result-backends`.
  135. Now with the result backend configured, let's execute the task again.
  136. This time we'll hold on to the :class:`~celery.result.AsyncResult`::
  137. >>> result = add.delay(4, 4)
  138. Here's some examples of what you can do when you have results::
  139. >>> result.ready() # returns True if the task has finished processing.
  140. False
  141. >>> result.result # task is not ready, so no return value yet.
  142. None
  143. >>> result.get() # Waits until the task is done and returns the retval.
  144. 8
  145. >>> result.result # direct access to result, doesn't re-raise errors.
  146. 8
  147. >>> result.successful() # returns True if the task didn't end in failure.
  148. True
  149. If the task raises an exception, the return value of `result.successful()`
  150. will be :const:`False`, and `result.result` will contain the exception instance
  151. raised by the task.
  152. Where to go from here
  153. =====================
  154. After this you should read the :ref:`guide`. Specifically
  155. :ref:`guide-tasks` and :ref:`guide-executing`.