README 11 KB

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