README.rst 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. ============================================
  2. celery - Distributed Task Queue for Django.
  3. ============================================
  4. :Version: 0.2.10
  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 Documentation`_ is hosted at Github
  47. (http://ask.github.com/celery)
  48. .. _`API Reference Docmentation`: 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. If you have downloaded a source tarball you can install it
  58. by doing the following,::
  59. $ python setup.py build
  60. # python setup.py install # as root
  61. Usage
  62. =====
  63. Installing RabbitMQ
  64. -------------------
  65. Configuring your Django project
  66. -------------------------------
  67. Running the celery worker daemon
  68. --------------------------------
  69. To test this we'll be running the worker daemon in the foreground, so we can
  70. see what's going on without consulting the logfile::
  71. ::
  72. $ python manage.py celeryd
  73. However, in production you'll probably want to run the worker in the
  74. background as daemon instead::
  75. $ python manage.py celeryd --daemon
  76. For help on command line arguments to the worker daemon, you can execute the
  77. help command::
  78. $ python manage.py help celeryd
  79. **Note**: If you're using ``SQLite`` as the Django database back-end,
  80. ``celeryd`` will only be able to process one task at a time, this is
  81. because ``SQLite`` doesn't allow concurrent writes.
  82. Defining and executing tasks
  83. ----------------------------
  84. **Please note** All of these tasks has to be stored in a real module, they can't
  85. be defined in the python shell or ipython/bpython. This is because the celery
  86. worker server needs access to the task function to be able to run it.
  87. So while it looks like we use the python shell to define the tasks in these
  88. examples, you can't do it this way. Put them in your Django applications
  89. ``tasks`` module (the worker daemon will automatically load any ``tasks.py``
  90. file for all of the applications listed in ``settings.INSTALLED_APPS``.
  91. Execution tasks using ``delay`` and ``apply_async`` can be done from the
  92. python shell, but keep in mind that since arguments are pickled, you can't
  93. use custom classes defined in the shell session.
  94. While you can use regular functions, the recommended way is creating
  95. a task class, this way you can cleanly upgrade the task to use the more
  96. advanced features of celery later.
  97. This is a task that basically does nothing but take some arguments,
  98. and return value:
  99. >>> class MyTask(Task):
  100. ... name = "myapp.mytask"
  101. ... def run(self, some_arg, **kwargs):
  102. ... logger = self.get_logger(**kwargs)
  103. ... logger.info("Did something: %s" % some_arg)
  104. ... return 42
  105. >>> tasks.register(MyTask)
  106. Now if we want to execute this task, we can use the ``delay`` method of the
  107. task class (this is a handy shortcut to the ``apply_async`` method which gives
  108. you greater control of the task execution).
  109. >>> from myapp.tasks import MyTask
  110. >>> MyTask.delay(some_arg="foo")
  111. At this point, the task has been sent to the message broker. The message
  112. broker will hold on to the task until a celery worker server has successfully
  113. picked it up.
  114. Now the task has been executed, but to know what happened with the task we
  115. have to check the celery logfile to see its return value and output.
  116. This is because we didn't keep the ``AsyncResult`` object returned by
  117. ``delay``.
  118. The ``AsyncResult`` lets us find out the state of the task, wait for the task to
  119. finish and get its return value (or exception if the task failed).
  120. So, let's execute the task again, but this time we'll keep track of the task:
  121. >>> result = MyTask.delay("do_something", some_arg="foo bar baz")
  122. >>> result.ready() # returns True if the task has finished processing.
  123. False
  124. >>> result.result # task is not ready, so no return value yet.
  125. None
  126. >>> result.get() # Waits until the task is done and return the retval.
  127. 42
  128. >>> result.result
  129. 42
  130. >>> result.success() # returns True if the task didn't end in failure.
  131. True
  132. If the task raises an exception, the ``result.success()`` will be ``False``,
  133. and ``result.result`` will contain the exception instance raised.
  134. Auto-discovery of tasks
  135. -----------------------
  136. ``celery`` has an auto-discovery feature like the Django Admin, that
  137. automatically loads any ``tasks.py`` module in the applications listed
  138. in ``settings.INSTALLED_APPS``. This autodiscovery is used by the celery
  139. worker to find registered tasks for your Django project.
  140. Periodic Tasks
  141. ---------------
  142. Periodic tasks are tasks that are run every ``n`` seconds.
  143. Here's an example of a periodic task:
  144. >>> from celery.task import tasks, PeriodicTask
  145. >>> from datetime import timedelta
  146. >>> class MyPeriodicTask(PeriodicTask):
  147. ... name = "foo.my-periodic-task"
  148. ... run_every = timedelta(seconds=30)
  149. ...
  150. ... def run(self, **kwargs):
  151. ... logger = self.get_logger(**kwargs)
  152. ... logger.info("Running periodic task!")
  153. ...
  154. >>> tasks.register(MyPeriodicTask)
  155. **Note:** Periodic tasks does not support arguments, as this doesn't
  156. really make sense.
  157. For periodic tasks to work you need to add ``celery`` to ``INSTALLED_APPS``,
  158. and issue a ``syncdb``.
  159. License
  160. =======
  161. This software is licensed under the ``New BSD License``. See the ``LICENSE``
  162. file in the top distribution directory for the full license text.
  163. .. # vim: syntax=rst expandtab tabstop=4 shiftwidth=4 shiftround