first-steps-with-celery.rst 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. .. _tut-celery:
  2. ========================
  3. First steps with Celery
  4. ========================
  5. .. contents::
  6. :local:
  7. .. _celerytut-broker:
  8. Choosing a Broker
  9. =================
  10. Celery requires a solution to send and receive messages, this is called
  11. the *message transport*. Usually this comes in the form of a separate
  12. service called a *message broker*.
  13. There are several choices available, including:
  14. * :ref:`broker-rabbitmq`
  15. `RabbitMQ`_ is feature-complete, stable, durable and easy to install.
  16. * :ref:`broker-redis`
  17. `Redis`_ is also feature-complete, but is more susceptible to data loss in
  18. the event of abrupt termination or power failures.
  19. * :ref:`broker-sqlalchemy`
  20. * :ref:`broker-django`
  21. Using a database as a message queue is not recommended, but can be sufficient
  22. for very small installations. Celery can use the SQLAlchemy and Django ORM.
  23. * and more.
  24. In addition to the above, there are several other transport implementations
  25. to choose from, including :ref:`broker-couchdb`, :ref:`broker-beanstalk`,
  26. :ref:`broker-mongodb`, and SQS. There is a `Transport Comparison`_
  27. in the Kombu documentation.
  28. .. _`RabbitMQ`: http://www.rabbitmq.com/
  29. .. _`Redis`: http://redis.io/
  30. .. _`Transport Comparison`: http://kombu.rtfd.org/transport-comparison
  31. .. _celerytut-conf:
  32. Application
  33. ===========
  34. The first thing you need is a Celery instance. Since the instance is used as
  35. the entry-point for everything you want to do in Celery, like creating task and
  36. managing workers, it must be possible for other modules to import it.
  37. Some people create a dedicated module for it, but in this tutorial we will
  38. keep it in the same module used to start our worker.
  39. Let's create the file :file:`worker.py`:
  40. .. code-block:: python
  41. from celery import Celery
  42. celery = Celery(broker="amqp://guest:guest@localhost:5672")
  43. if __name__ == "__main__":
  44. celery.worker_main()
  45. The broker argument specifies the message broker we want to use, what
  46. we are using in this example is the default, but we keep it there for
  47. reference so you can see what the URLs look like.
  48. By default the state and return value (results) of the tasks are ignored,
  49. if you want to enable this please see :ref:`celerytut-keeping-results`.
  50. That's all you need to get started!
  51. If you want to dig deeper there are lots of configuration possibilities that
  52. can be applied. For example you can set the default value for the workers
  53. `--concurrency`` argument, which is used to decide the number of pool worker
  54. processes, the name for this setting is :setting:`CELERYD_CONCURRENCY`:
  55. .. code-block:: python
  56. celery.conf.CELERY_CONCURRENCY = 10
  57. If you are configuring many settings then one practice is to have a separate module
  58. containing the configuration. You can tell your Celery instance to use
  59. this module, historically called ``celeryconfig.py``, with the
  60. :meth:`config_from_obj` method:
  61. .. code-block:: python
  62. celery.config_from_object("celeryconfig")
  63. For a complete reference of configuration options, see :ref:`configuration`.
  64. .. _celerytut-simple-tasks:
  65. Creating a simple task
  66. ======================
  67. In this tutorial we are creating a simple task that adds two
  68. numbers. Tasks are defined in normal Python modules.
  69. By convention we will call our module :file:`tasks.py`, and it looks
  70. like this:
  71. :file: `tasks.py`
  72. .. code-block:: python
  73. from worker import celery
  74. @celery.task
  75. def add(x, y):
  76. return x + y
  77. .. seealso::
  78. The full documentation on how to create tasks and task classes is in the
  79. :doc:`../userguide/tasks` part of the user guide.
  80. .. _celerytut-running-celeryd:
  81. Running the celery worker server
  82. ================================
  83. We can now run our ``worker.py`` program::
  84. $ python worker.py --loglevel=INFO
  85. In production you will probably want to run the worker in the
  86. background as a daemon. To do this you need to use the tools provided
  87. by your platform, or something like `supervisord`_ (see :ref:`daemonizing`
  88. for more information).
  89. For a complete listing of the command line options available, do::
  90. $ python worker.py --help
  91. .. _`supervisord`: http://supervisord.org
  92. .. _celerytut-executing-task:
  93. Executing the task
  94. ==================
  95. Whenever we want to execute our task, we use the
  96. :meth:`~celery.task.base.Task.delay` method of the task class.
  97. This is a handy shortcut to the :meth:`~celery.task.base.Task.apply_async`
  98. method which gives greater control of the task execution (see
  99. :ref:`guide-executing`).
  100. >>> from tasks import add
  101. >>> add.delay(4, 4)
  102. <AsyncResult: 889143a6-39a2-4e52-837b-d80d33efb22d>
  103. At this point, the task has been sent to the message broker. The message
  104. broker will hold on to the task until a worker server has consumed and
  105. executed it.
  106. Right now we have to check the worker log files to know what happened
  107. with the task. Applying a task returns an
  108. :class:`~celery.result.AsyncResult`, if you have configured a result store
  109. the :class:`~celery.result.AsyncResult` enables you to check the state of
  110. the task, wait for the task to finish, get its return value
  111. or exception/traceback if the task failed, and more.
  112. .. _celerytut-keeping-results:
  113. Keeping Results
  114. ---------------
  115. If you want to keep track of the tasks state, Celery needs to store or send
  116. the states somewhere. There are several
  117. built-in backends to choose from: SQLAlchemy/Django ORM, Memcached, Redis,
  118. AMQP, MongoDB, Tokyo Tyrant and Redis -- or you can define your own.
  119. For this example we will use the `amqp` result backend, which sends states
  120. as messages. The backend is configured via the :setting:`CELERY_RESULT_BACKEND`
  121. setting or using the ``backend`` argument to :class:`Celery`, in addition individual
  122. result backends may have additional settings
  123. you can configure::
  124. from celery.backends.amqp import AMQPBackend
  125. celery = Celery(backend=AMQPBackend(expires=300))
  126. To read more about result backends please see :ref:`task-result-backends`.
  127. Now with the result backend configured, let's execute the task again.
  128. This time we'll hold on to the :class:`~celery.result.AsyncResult`::
  129. >>> result = add.delay(4, 4)
  130. Here's some examples of what you can do when you have results::
  131. >>> result.ready() # returns True if the task has finished processing.
  132. False
  133. >>> result.result # task is not ready, so no return value yet.
  134. None
  135. >>> result.get() # Waits until the task is done and returns the retval.
  136. 8
  137. >>> result.result # direct access to result, doesn't re-raise errors.
  138. 8
  139. >>> result.successful() # returns True if the task didn't end in failure.
  140. True
  141. If the task raises an exception, the return value of `result.successful()`
  142. will be :const:`False`, and `result.result` will contain the exception instance
  143. raised by the task.
  144. Where to go from here
  145. =====================
  146. After this you should read the :ref:`guide`. Specifically
  147. :ref:`guide-tasks` and :ref:`guide-executing`.