README.rst 13 KB

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