introduction.rst 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. =================================
  2. celery - Distributed Task Queue
  3. =================================
  4. :Version: 0.9.0
  5. Introduction
  6. ============
  7. Celery is a distributed task queue.
  8. It was first created for Django, but is now usable from Python.
  9. It can also operate with other languages via HTTP+JSON.
  10. This introduction is written for someone who wants to use
  11. Celery from within a Django project. For information about using it from
  12. pure Python see `Can I use Celery without Django?`_, for calling out to other
  13. languages see `Executing tasks on a remote web server`_.
  14. .. _`Can I use Celery without Django?`: http://bit.ly/WPa6n
  15. .. _`Executing tasks on a remote web server`: http://bit.ly/CgXSc
  16. It is used for executing tasks *asynchronously*, routed to one or more
  17. worker servers, running concurrently using multiprocessing.
  18. Overview
  19. ========
  20. This is a high level overview of the architecture.
  21. .. image:: http://cloud.github.com/downloads/ask/celery/Celery-Overview-v4.jpg
  22. The broker pushes tasks to the worker servers.
  23. A worker server is a networked machine running ``celeryd``. This can be one or
  24. more machines, depending on the workload.
  25. The result of the task can be stored for later retrieval (called its
  26. "tombstone").
  27. Features
  28. ========
  29. * Uses AMQP messaging (RabbitMQ, ZeroMQ, Qpid) to route tasks to the
  30. worker servers. Experimental support for STOMP (ActiveMQ) is also
  31. available.
  32. * For simple setups it's also possible to use Redis or an SQL database
  33. as the message queue.
  34. * You can run as many worker servers as you want, and still
  35. be *guaranteed that the task is only executed once.*
  36. * Tasks are executed *concurrently* using the Python 2.6
  37. `:mod:`multiprocessing` module (also available as a back-port
  38. to older python versions)
  39. * Supports *periodic tasks*, which makes it a (better) replacement
  40. for cronjobs.
  41. * When a task has been executed, the return value can be stored using
  42. either a MySQL/Oracle/PostgreSQL/SQLite database, Memcached,
  43. `MongoDB`_, `Redis`_ or `Tokyo Tyrant`_ back-end. For high-performance
  44. you can also use AMQP messages to publish results.
  45. * Supports calling tasks over HTTP to support multiple programming
  46. languages and systems.
  47. * Supports several serialization schemes, like pickle, json, yaml and
  48. supports registering custom encodings .
  49. * If the task raises an exception, the exception instance is stored,
  50. instead of the return value, and it's possible to inspect the traceback
  51. after the fact.
  52. * All tasks has a Universally Unique Identifier (UUID), which is the
  53. task id, used for querying task status and return values.
  54. * Tasks can be retried if they fail, with a configurable maximum number
  55. of retries.
  56. * Tasks can be configured to run at a specific time and date in the
  57. future (ETA) or you can set a countdown in seconds for when the
  58. task should be executed.
  59. * Supports *task-sets*, which is a task consisting of several sub-tasks.
  60. You can find out how many, or if all of the sub-tasks has been executed.
  61. Excellent for progress-bar like functionality.
  62. * Has a ``map`` like function that uses tasks,
  63. called :func:`celery.task.dmap`.
  64. * However, you rarely want to wait for these results in a web-environment.
  65. You'd rather want to use Ajax to poll the task status, which is
  66. available from a URL like ``celery/<task_id>/status/``. This view
  67. returns a JSON-serialized data structure containing the task status,
  68. and the return value if completed, or exception on failure.
  69. * The worker can collect statistics, like, how many tasks has been
  70. executed by type, and the time it took to process them. Very useful
  71. for monitoring and profiling.
  72. * Pool workers are supervised, so if for some reason a worker crashes
  73. it is automatically replaced by a new worker.
  74. * Can be configured to send e-mails to the administrators when a task
  75. fails.
  76. .. _`MongoDB`: http://www.mongodb.org/
  77. .. _`Redis`: http://code.google.com/p/redis/
  78. .. _`Tokyo Tyrant`: http://tokyocabinet.sourceforge.net/
  79. API Reference Documentation
  80. ===========================
  81. The `API Reference`_ is hosted at Github
  82. (http://ask.github.com/celery)
  83. .. _`API Reference`: http://ask.github.com/celery/
  84. Installation
  85. =============
  86. You can install ``celery`` either via the Python Package Index (PyPI)
  87. or from source.
  88. To install using ``pip``,::
  89. $ pip install celery
  90. To install using ``easy_install``,::
  91. $ easy_install celery
  92. Downloading and installing from source
  93. --------------------------------------
  94. Download the latest version of ``celery`` from
  95. http://pypi.python.org/pypi/celery/
  96. You can install it by doing the following,::
  97. $ tar xvfz celery-0.0.0.tar.gz
  98. $ cd celery-0.0.0
  99. $ python setup.py build
  100. # python setup.py install # as root
  101. Using the development version
  102. ------------------------------
  103. You can clone the repository by doing the following::
  104. $ git clone git://github.com/ask/celery.git
  105. Usage
  106. =====
  107. Installing RabbitMQ
  108. -------------------
  109. See `Installing RabbitMQ`_ over at RabbitMQ's website. For Mac OS X
  110. see `Installing RabbitMQ on OS X`_.
  111. .. _`Installing RabbitMQ`: http://www.rabbitmq.com/install.html
  112. .. _`Installing RabbitMQ on OS X`:
  113. http://playtype.net/past/2008/10/9/installing_rabbitmq_on_osx/
  114. Setting up RabbitMQ
  115. -------------------
  116. To use celery we need to create a RabbitMQ user, a virtual host and
  117. allow that user access to that virtual host::
  118. $ rabbitmqctl add_user myuser mypassword
  119. $ rabbitmqctl add_vhost myvhost
  120. From RabbitMQ version 1.6.0 and onward you have to use the new ACL features
  121. to allow access::
  122. $ rabbitmqctl set_permissions -p myvhost myuser "" ".*" ".*"
  123. See the RabbitMQ `Admin Guide`_ for more information about `access control`_.
  124. .. _`Admin Guide`: http://www.rabbitmq.com/admin-guide.html
  125. .. _`access control`: http://www.rabbitmq.com/admin-guide.html#access-control
  126. If you are still using version 1.5.0 or below, please use ``map_user_vhost``::
  127. $ rabbitmqctl map_user_vhost myuser myvhost
  128. Configuring your Django project to use Celery
  129. ---------------------------------------------
  130. You only need three simple steps to use celery with your Django project.
  131. 1. Add ``celery`` to ``INSTALLED_APPS``.
  132. 2. Create the celery database tables::
  133. $ python manage.py syncdb
  134. 3. Configure celery to use the AMQP user and virtual host we created
  135. before, by adding the following to your ``settings.py``::
  136. AMQP_SERVER = "localhost"
  137. AMQP_PORT = 5672
  138. AMQP_USER = "myuser"
  139. AMQP_PASSWORD = "mypassword"
  140. AMQP_VHOST = "myvhost"
  141. That's it.
  142. There are more options available, like how many processes you want to process
  143. work in parallel (the ``CELERY_CONCURRENCY`` setting), and the backend used
  144. for storing task statuses. But for now, this should do. For all of the options
  145. available, please consult the `API Reference`_
  146. **Note**: If you're using SQLite as the Django database back-end,
  147. ``celeryd`` will only be able to process one task at a time, this is
  148. because SQLite doesn't allow concurrent writes.
  149. Running the celery worker server
  150. --------------------------------
  151. To test this we'll be running the worker server in the foreground, so we can
  152. see what's going on without consulting the logfile::
  153. $ python manage.py celeryd
  154. However, in production you probably want to run the worker in the
  155. background, as a daemon::
  156. $ python manage.py celeryd --detach
  157. For a complete listing of the command line arguments available, with a short
  158. description, you can use the help command::
  159. $ python manage.py help celeryd
  160. Defining and executing tasks
  161. ----------------------------
  162. **Please note** All of these tasks has to be stored in a real module, they can't
  163. be defined in the python shell or ipython/bpython. This is because the celery
  164. worker server needs access to the task function to be able to run it.
  165. Put them in the ``tasks`` module of your
  166. Django application. The worker server will automatically load any ``tasks.py``
  167. file for all of the applications listed in ``settings.INSTALLED_APPS``.
  168. Executing tasks using ``delay`` and ``apply_async`` can be done from the
  169. python shell, but keep in mind that since arguments are pickled, you can't
  170. use custom classes defined in the shell session.
  171. This is a task that adds two numbers:
  172. .. code-block:: python
  173. from celery.decorators import task
  174. @task()
  175. def add(x, y):
  176. return x + y
  177. You can also use the workers logger to add some diagnostic output to
  178. the worker log:
  179. .. code-block:: python
  180. from celery.decorators import task
  181. @task()
  182. def add(x, y, **kwargs):
  183. logger = add.get_logger(**kwargs)
  184. logger.info("Adding %s + %s" % (x, y))
  185. return x + y
  186. As you can see the worker is sending some keyword arguments to this task,
  187. this is the default keyword arguments. A task can choose not to take these,
  188. or only list the ones it want (the worker will do the right thing).
  189. The current default keyword arguments are:
  190. * logfile
  191. The currently used log file, can be passed on to ``self.get_logger``
  192. to gain access to the workers log file via a ``logger.Logging``
  193. instance.
  194. * loglevel
  195. The current loglevel used.
  196. * task_id
  197. The unique id of the executing task.
  198. * task_name
  199. Name of the executing task.
  200. * task_retries
  201. How many times the current task has been retried.
  202. (an integer starting a ``0``).
  203. Now if we want to execute this task, we can use the
  204. ``delay`` method of the task class.
  205. This is a handy shortcut to the ``apply_async`` method which gives
  206. greater control of the task execution (see :doc:`userguide/executing` for more
  207. information).
  208. >>> from myapp.tasks import MyTask
  209. >>> MyTask.delay(some_arg="foo")
  210. At this point, the task has been sent to the message broker. The message
  211. broker will hold on to the task until a celery worker server has successfully
  212. picked it up.
  213. *Note* If everything is just hanging when you execute ``delay``, please check
  214. that RabbitMQ is running, and that the user/password has access to the virtual
  215. host you configured earlier.
  216. Right now we have to check the celery worker logfiles to know what happened with
  217. the task. This is because we didn't keep the ``AsyncResult`` object returned
  218. by ``delay``.
  219. The ``AsyncResult`` lets us find the state of the task, wait for the task to
  220. finish and get its return value (or exception if the task failed).
  221. So, let's execute the task again, but this time we'll keep track of the task:
  222. >>> result = add.delay(4, 4)
  223. >>> result.ready() # returns True if the task has finished processing.
  224. False
  225. >>> result.result # task is not ready, so no return value yet.
  226. None
  227. >>> result.get() # Waits until the task is done and returns the retval.
  228. 8
  229. >>> result.result # direct access to result, doesn't re-raise errors.
  230. 8
  231. >>> result.successful() # returns True if the task didn't end in failure.
  232. True
  233. If the task raises an exception, the return value of ``result.successful()``
  234. will be ``False``, and ``result.result`` will contain the exception instance
  235. raised by the task.
  236. Worker auto-discovery of tasks
  237. ------------------------------
  238. ``celeryd`` has an auto-discovery feature like the Django Admin, that
  239. automatically loads any ``tasks.py`` module in the applications listed
  240. in ``settings.INSTALLED_APPS``. This autodiscovery is used by the celery
  241. worker to find registered tasks for your Django project.
  242. Periodic Tasks
  243. ---------------
  244. Periodic tasks are tasks that are run every ``n`` seconds.
  245. Here's an example of a periodic task:
  246. .. code-block:: python
  247. from celery.task import PeriodicTask
  248. from celery.registry import tasks
  249. from datetime import timedelta
  250. class MyPeriodicTask(PeriodicTask):
  251. run_every = timedelta(seconds=30)
  252. def run(self, **kwargs):
  253. logger = self.get_logger(**kwargs)
  254. logger.info("Running periodic task!")
  255. >>> tasks.register(MyPeriodicTask)
  256. A look inside the components
  257. ============================
  258. .. image:: http://cloud.github.com/downloads/ask/celery/Celery1.0-inside-worker.jpg
  259. Getting Help
  260. ============
  261. Mailing list
  262. ------------
  263. For discussions about the usage, development, and future of celery,
  264. please join the `celery-users`_ mailing list.
  265. .. _`celery-users`: http://groups.google.com/group/celery-users/
  266. IRC
  267. ---
  268. Come chat with us on IRC. The `#celery`_ channel is located at the `Freenode`_
  269. network.
  270. .. _`#celery`: irc://irc.freenode.net/celery
  271. .. _`Freenode`: http://freenode.net
  272. Bug tracker
  273. ===========
  274. If you have any suggestions, bug reports or annoyances please report them
  275. to our issue tracker at http://github.com/ask/celery/issues/
  276. Contributing
  277. ============
  278. Development of ``celery`` happens at Github: http://github.com/ask/celery
  279. You are highly encouraged to participate in the development
  280. of ``celery``. If you don't like Github (for some reason) you're welcome
  281. to send regular patches.
  282. License
  283. =======
  284. This software is licensed under the ``New BSD License``. See the ``LICENSE``
  285. file in the top distribution directory for the full license text.
  286. .. # vim: syntax=rst expandtab tabstop=4 shiftwidth=4 shiftround