README 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. ============================================
  2. celery - Distributed Task Queue for Django.
  3. ============================================
  4. :Version: 0.3.7
  5. Introduction
  6. ============
  7. ``celery`` is a distributed task queue framework for Django.
  8. It is used for executing tasks *asynchronously*, routed to one or more
  9. worker servers, running concurrently using multiprocessing.
  10. It is designed to solve certain problems related to running websites
  11. demanding high-availability and performance.
  12. It is perfect for filling caches, posting updates to twitter, mass
  13. downloading data like syndication feeds or web scraping. Use-cases are
  14. plentiful. Implementing these features asynchronously using ``celery`` is
  15. easy and fun, and the performance improvements can make it more than
  16. worthwhile.
  17. Features
  18. ========
  19. * Uses AMQP messaging (RabbitMQ, ZeroMQ) to route tasks to the
  20. worker servers.
  21. * You can run as many worker servers as you want, and still
  22. be *guaranteed that the task is only executed once.*
  23. * Tasks are executed *concurrently* using the Python 2.6
  24. ``multiprocessing`` module (also available as a back-port
  25. to older python versions)
  26. * Supports *periodic tasks*, which makes it a (better) replacement
  27. for cronjobs.
  28. * When a task has been executed, the return value is stored using either
  29. a MySQL/Oracle/PostgreSQL/SQLite database, memcached,
  30. or Tokyo Tyrant back-end.
  31. * If the task raises an exception, the exception instance is stored,
  32. instead of the return value.
  33. * All tasks has a Universally Unique Identifier (UUID), which is the
  34. task id, used for querying task status and return values.
  35. * Supports *task-sets*, which is a task consisting of several sub-tasks.
  36. You can find out how many, or if all of the sub-tasks has been executed.
  37. Excellent for progress-bar like functionality.
  38. * Has a ``map`` like function that uses tasks, called ``dmap``.
  39. * However, you rarely want to wait for these results in a web-environment.
  40. You'd rather want to use Ajax to poll the task status, which is
  41. available from a URL like ``celery/<task_id>/status/``. This view
  42. returns a JSON-serialized data structure containing the task status,
  43. and the return value if completed, or exception on failure.
  44. API Reference Documentation
  45. ===========================
  46. The `API Reference`_ is hosted at Github
  47. (http://ask.github.com/celery)
  48. .. _`API Reference`: http://ask.github.com/celery/
  49. Installation
  50. =============
  51. You can install ``celery`` either via the Python Package Index (PyPI)
  52. or from source.
  53. To install using ``pip``,::
  54. $ pip install celery
  55. To install using ``easy_install``,::
  56. $ easy_install celery
  57. Downloading and installing from source
  58. --------------------------------------
  59. Download the latest version of ``celery`` from
  60. http://pypi.python.org/pypi/celery/
  61. You can install it by doing the following,::
  62. $ tar xvfz celery-0.0.0.tar.gz
  63. $ cd celery-0.0.0
  64. $ python setup.py build
  65. # python setup.py install # as root
  66. Using the development version
  67. ------------------------------
  68. You can clone the repository by doing the following::
  69. $ git clone git://github.com/ask/celery.git celery
  70. Usage
  71. =====
  72. Installing RabbitMQ
  73. -------------------
  74. See `Installing RabbitMQ`_ over at RabbitMQ's website. For Mac OS X
  75. see `Installing RabbitMQ on OS X`_.
  76. .. _`Installing RabbitMQ`: http://www.rabbitmq.com/install.html
  77. .. _`Installing RabbitMQ on OS X`:
  78. http://playtype.net/past/2008/10/9/installing_rabbitmq_on_osx/
  79. Setting up RabbitMQ
  80. -------------------
  81. To use celery we need to create a RabbitMQ user, a virtual host and
  82. allow that user access to that virtual host::
  83. $ rabbitmqctl add_user myuser mypassword
  84. $ rabbitmqctl add_vhost myvhost
  85. $ rabbitmqctl map_user_vhost myuser myvhost
  86. Configuring your Django project to use Celery
  87. ---------------------------------------------
  88. You only need three simple steps to use celery with your Django project.
  89. 1. Add ``celery`` to ``INSTALLED_APPS``.
  90. 2. Create the celery database tables::
  91. $ python manage.py syncdb
  92. 3. Configure celery to use the AMQP user and virtual host we created
  93. before, by adding the following to your ``settings.py``::
  94. AMQP_SERVER = "localhost"
  95. AMQP_PORT = 5672
  96. AMQP_USER = "myuser"
  97. AMQP_PASSWORD = "mypassword"
  98. AMQP_VHOST = "myvhost"
  99. That's it.
  100. There are more options available, like how many processes you want to process
  101. work in parallel (the ``CELERY_CONCURRENCY`` setting), and the backend used
  102. for storing task statuses. But for now, this should do. For all of the options
  103. available, please consult the `API Reference`_
  104. **Note**: If you're using SQLite as the Django database back-end,
  105. ``celeryd`` will only be able to process one task at a time, this is
  106. because SQLite doesn't allow concurrent writes.
  107. Running the celery worker server
  108. --------------------------------
  109. To test this we'll be running the worker server in the foreground, so we can
  110. see what's going on without consulting the logfile::
  111. $ python manage.py celeryd
  112. However, in production you'll probably want to run the worker in the
  113. background as a daemon instead::
  114. $ python manage.py celeryd --detach
  115. For help on command line arguments to the worker server, you can execute the
  116. help command::
  117. $ python manage.py help celeryd
  118. Defining and executing tasks
  119. ----------------------------
  120. **Please note** All of these tasks has to be stored in a real module, they can't
  121. be defined in the python shell or ipython/bpython. This is because the celery
  122. worker server needs access to the task function to be able to run it.
  123. So while it looks like we use the python shell to define the tasks in these
  124. examples, you can't do it this way. Put them in the ``tasks`` module of your
  125. Django application. The worker server will automatically load any ``tasks.py``
  126. file for all of the applications listed in ``settings.INSTALLED_APPS``.
  127. Executing tasks using ``delay`` and ``apply_async`` can be done from the
  128. python shell, but keep in mind that since arguments are pickled, you can't
  129. use custom classes defined in the shell session.
  130. While you can use regular functions, the recommended way is to define
  131. a task class. With this way you can cleanly upgrade the task to use the more
  132. advanced features of celery later.
  133. This is a task that basically does nothing but take some arguments,
  134. and return a value:
  135. >>> from celery.task import Task, tasks
  136. >>> class MyTask(Task):
  137. ... name = "myapp.mytask"
  138. ... def run(self, some_arg, **kwargs):
  139. ... logger = self.get_logger(**kwargs)
  140. ... logger.info("Did something: %s" % some_arg)
  141. ... return 42
  142. >>> tasks.register(MyTask)
  143. Now if we want to execute this task, we can use the ``delay`` method of the
  144. task class (this is a handy shortcut to the ``apply_async`` method which gives
  145. you greater control of the task execution).
  146. >>> from myapp.tasks import MyTask
  147. >>> MyTask.delay(some_arg="foo")
  148. At this point, the task has been sent to the message broker. The message
  149. broker will hold on to the task until a celery worker server has successfully
  150. picked it up.
  151. Right now we have to check the celery worker logfiles to know what happened with
  152. the task. This is because we didn't keep the ``AsyncResult`` object returned
  153. by ``delay``.
  154. The ``AsyncResult`` lets us find the state of the task, wait for the task to
  155. finish and get its return value (or exception if the task failed).
  156. So, let's execute the task again, but this time we'll keep track of the task:
  157. >>> result = MyTask.delay("do_something", some_arg="foo bar baz")
  158. >>> result.ready() # returns True if the task has finished processing.
  159. False
  160. >>> result.result # task is not ready, so no return value yet.
  161. None
  162. >>> result.get() # Waits until the task is done and return the retval.
  163. 42
  164. >>> result.result
  165. 42
  166. >>> result.success() # returns True if the task didn't end in failure.
  167. True
  168. If the task raises an exception, the ``result.success()`` will be ``False``,
  169. and ``result.result`` will contain the exception instance raised.
  170. Auto-discovery of tasks
  171. -----------------------
  172. ``celery`` has an auto-discovery feature like the Django Admin, that
  173. automatically loads any ``tasks.py`` module in the applications listed
  174. in ``settings.INSTALLED_APPS``. This autodiscovery is used by the celery
  175. worker to find registered tasks for your Django project.
  176. Periodic Tasks
  177. ---------------
  178. Periodic tasks are tasks that are run every ``n`` seconds.
  179. Here's an example of a periodic task:
  180. >>> from celery.task import tasks, PeriodicTask
  181. >>> from datetime import timedelta
  182. >>> class MyPeriodicTask(PeriodicTask):
  183. ... name = "foo.my-periodic-task"
  184. ... run_every = timedelta(seconds=30)
  185. ...
  186. ... def run(self, **kwargs):
  187. ... logger = self.get_logger(**kwargs)
  188. ... logger.info("Running periodic task!")
  189. ...
  190. >>> tasks.register(MyPeriodicTask)
  191. **Note:** Periodic tasks does not support arguments, as this doesn't
  192. really make sense.
  193. Getting Help
  194. ============
  195. Mailing list
  196. ------------
  197. For discussions about the usage, development, and future of celery,
  198. please join the `celery-users`_ mailing list.
  199. .. _`celery-users`: http://groups.google.com/group/celery-users/
  200. IRC
  201. ---
  202. Come chat with us on IRC. The `#celery`_ channel is located at the `Freenode`_
  203. network.
  204. .. _`#celery`: irc://irc.freenode.net/celery
  205. .. _`Freenode`: http://freenode.net
  206. Bug tracker
  207. ===========
  208. If you have any suggestions, bug reports or annoyances please report them
  209. to our issue tracker at http://github.com/ask/celery/issues/
  210. Contributing
  211. ============
  212. Development of ``celery`` happens at Github: http://github.com/ask/celery
  213. You are highly encouraged to participate in the development
  214. of ``celery``. If you don't like Github (for some reason) you're welcome
  215. to send regular patches.
  216. License
  217. =======
  218. This software is licensed under the ``New BSD License``. See the ``LICENSE``
  219. file in the top distribution directory for the full license text.
  220. .. # vim: syntax=rst expandtab tabstop=4 shiftwidth=4 shiftround