FAQ 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  1. ============================
  2. Frequently Asked Questions
  3. ============================
  4. General
  5. =======
  6. What kinds of things should I use celery for?
  7. ---------------------------------------------
  8. **Answer:** `Queue everything and delight everyone`_ is a good article
  9. describing why you would use a queue in a web context.
  10. .. _`Queue everything and delight everyone`:
  11. http://decafbad.com/blog/2008/07/04/queue-everything-and-delight-everyone
  12. These are some common use cases:
  13. * Running something in the background. For example, to finish the web request
  14. as soon as possible, then update the users page incrementally.
  15. This gives the user the impression of good performane and "snappiness", even
  16. though the real work might actually take some time.
  17. * Running something after the web request has finished.
  18. * Making sure something is done, by executing it asynchronously and using
  19. retries.
  20. * Scheduling periodic work.
  21. And to some degree:
  22. * Distributed computing.
  23. * Parallel execution.
  24. Misconceptions
  25. ==============
  26. Is celery dependent on pickle?
  27. ------------------------------
  28. **Answer:** No.
  29. Celery can support any serialization scheme and has support for JSON/YAML and
  30. Pickle by default. You can even send one task using pickle, and another one
  31. with JSON seamlessly, this is because every task is associated with a
  32. content-type. The default serialization scheme is pickle because it's the most
  33. used, and it has support for sending complex objects as task arguments.
  34. You can set a global default serializer, the default serializer for a
  35. particular Task, or even what serializer to use when sending a single task
  36. instance.
  37. Is celery for Django only?
  38. --------------------------
  39. **Answer:** No.
  40. You can use all of the features without using Django.
  41. Why is Django a dependency?
  42. ---------------------------
  43. Celery uses the Django ORM for database access when using the database result
  44. backend, the Django cache framework when using the cache result backend, and the Django signal
  45. dispatch mechanisms for signaling.
  46. This doesn't mean you need to have a Django project to use celery, it
  47. just means that sometimes we use internal Django components.
  48. The long term plan is to replace these with other solutions, (e.g. `SQLAlchemy`_ as the ORM,
  49. and `louie`_, for signaling). The celery distribution will be split into two:
  50. * celery
  51. The core. Using SQLAlchemy for the database backend.
  52. * django-celery
  53. Celery integration for Django, using the Django ORM for the database
  54. backend.
  55. We're currently seeking people with `SQLAlchemy`_ experience, so please
  56. contact the project if you want this done sooner.
  57. The reason for the split is for purity only. It shouldn't affect you much as a
  58. user, so please don't worry about the Django dependency, just have a good time
  59. using celery.
  60. .. _`SQLAlchemy`: http://www.sqlalchemy.org/
  61. .. _`louie`: http://pypi.python.org/pypi/Louie/
  62. Do I have to use AMQP/RabbitMQ?
  63. -------------------------------
  64. **Answer**: No.
  65. You can also use Redis or an SQL database, see `Using other
  66. queues`_.
  67. .. _`Using other queues`:
  68. http://ask.github.com/celery/tutorials/otherqueues.html
  69. Redis or a database won't perform as well as
  70. an AMQP broker. If you have strict reliability requirements you are
  71. encouraged to use RabbitMQ or another AMQP broker. Redis/database also use
  72. polling, so they are likely to consume more resources. However, if you for
  73. some reason are not able to use AMQP, feel free to use these alternatives.
  74. They will probably work fine for most use cases, and note that the above
  75. points are not specific to celery; If using Redis/database as a queue worked
  76. fine for you before, it probably will now. You can always upgrade later
  77. if you need to.
  78. Is celery multi-lingual?
  79. ------------------------
  80. **Answer:** Yes.
  81. celeryd is an implementation of celery in python. If the language has an AMQP
  82. client, there shouldn't be much work to create a worker in your language.
  83. A celery worker is just a program connecting to the broker to consume
  84. messages. There's no other communication involved.
  85. Also, there's another way to be language indepedent, and that is to use REST
  86. tasks, instead of your tasks being functions, they're URLs. With this
  87. information you can even create simple web servers that enable preloading of
  88. code. See: `User Guide: Remote Tasks`_.
  89. .. _`User Guide: Remote Tasks`:
  90. http://ask.github.com/celery/userguide/remote-tasks.html
  91. Troubleshooting
  92. ===============
  93. MySQL is throwing deadlock errors, what can I do?
  94. -------------------------------------------------
  95. **Answer:** MySQL has default isolation level set to ``REPEATABLE-READ``,
  96. if you don't really need that, set it to ``READ-COMMITTED``.
  97. You can do that by adding the following to your ``my.cnf``::
  98. [mysqld]
  99. transaction-isolation = READ-COMMITTED
  100. For more information about InnoDBs transaction model see `MySQL - The InnoDB
  101. Transaction Model and Locking`_ in the MySQL user manual.
  102. (Thanks to Honza Kral and Anton Tsigularov for this solution)
  103. .. _`MySQL - The InnoDB Transaction Model and Locking`: http://dev.mysql.com/doc/refman/5.1/en/innodb-transaction-model.html
  104. celeryd is not doing anything, just hanging
  105. --------------------------------------------
  106. **Answer:** See `MySQL is throwing deadlock errors, what can I do?`_.
  107. or `Why is Task.delay/apply\* just hanging?`.
  108. Why is Task.delay/apply\*/celeryd just hanging?
  109. -----------------------------------------------
  110. **Answer:** There is a bug in some AMQP clients that will make it hang if
  111. it's not able to authenticate the current user, the password doesn't match or
  112. the user does not have access to the virtual host specified. Be sure to check
  113. your broker logs (for RabbitMQ that is ``/var/log/rabbitmq/rabbit.log`` on
  114. most systems), it usually contains a message describing the reason.
  115. Why won't celeryd run on FreeBSD?
  116. ---------------------------------
  117. **Answer:** multiprocessing.Pool requires a working POSIX semaphore
  118. implementation which isn't enabled in FreeBSD by default. You have to enable
  119. POSIX semaphores in the kernel and manually recompile multiprocessing.
  120. Luckily, Viktor Petersson has written a tutorial to get you started with
  121. Celery on FreeBSD here:
  122. http://www.playingwithwire.com/2009/10/how-to-get-celeryd-to-work-on-freebsd/
  123. I'm having ``IntegrityError: Duplicate Key`` errors. Why?
  124. ---------------------------------------------------------
  125. **Answer:** See `MySQL is throwing deadlock errors, what can I do?`_.
  126. Thanks to howsthedotcom.
  127. Why aren't my tasks processed?
  128. ------------------------------
  129. **Answer:** With RabbitMQ you can see how many consumers are currently
  130. receiving tasks by running the following command::
  131. $ rabbitmqctl list_queues -p <myvhost> name messages consumers
  132. Listing queues ...
  133. celery 2891 2
  134. This shows that there's 2891 messages waiting to be processed in the task
  135. queue, and there are two consumers processing them.
  136. One reason that the queue is never emptied could be that you have a stale
  137. celery process taking the messages hostage. This could happen if celeryd
  138. wasn't properly shut down.
  139. When a message is recieved by a worker the broker waits for it to be
  140. acknowledged before marking the message as processed. The broker will not
  141. re-send that message to another consumer until the consumer is shut down
  142. properly.
  143. If you hit this problem you have to kill all workers manually and restart
  144. them::
  145. ps auxww | grep celeryd | awk '{print $2}' | xargs kill
  146. You might have to wait a while until all workers have finished the work they're
  147. doing. If it's still hanging after a long time you can kill them by force
  148. with::
  149. ps auxww | grep celeryd | awk '{print $2}' | xargs kill -9
  150. Why won't my Task run?
  151. ----------------------
  152. **Answer:** Did you register the task in the applications ``tasks.py`` module?
  153. (or in some other module Django loads by default, like ``models.py``?).
  154. Also there might be syntax errors preventing the tasks module being imported.
  155. You can find out if celery is able to run the task by executing the
  156. task manually:
  157. >>> from myapp.tasks import MyPeriodicTask
  158. >>> MyPeriodicTask.delay()
  159. Watch celeryds logfile to see if it's able to find the task, or if some
  160. other error is happening.
  161. Why won't my Periodic Task run?
  162. -------------------------------
  163. **Answer:** See `Why won't my Task run?`_.
  164. How do I discard all waiting tasks?
  165. ------------------------------------
  166. **Answer:** Use ``celery.task.discard_all()``, like this:
  167. >>> from celery.task import discard_all
  168. >>> discard_all()
  169. 1753
  170. The number ``1753`` is the number of messages deleted.
  171. You can also start celeryd with the ``--discard`` argument which will
  172. accomplish the same thing.
  173. I've discarded messages, but there are still messages left in the queue?
  174. ------------------------------------------------------------------------
  175. **Answer:** Tasks are acknowledged (removed from the queue) as soon
  176. as they are actually executed. After the worker has received a task, it will
  177. take some time until it is actually executed, especially if there are a lot
  178. of tasks already waiting for execution. Messages that are not acknowledged are
  179. hold on to by the worker until it closes the connection to the broker (AMQP
  180. server). When that connection is closed (e.g because the worker was stopped)
  181. the tasks will be re-sent by the broker to the next available worker (or the
  182. same worker when it has been restarted), so to properly purge the queue of
  183. waiting tasks you have to stop all the workers, and then discard the tasks
  184. using ``discard_all``.
  185. Brokers
  186. =======
  187. Can I use celery with ActiveMQ/STOMP?
  188. -------------------------------------
  189. **Answer**: Yes, but this is somewhat experimental for now.
  190. It is working ok in a test configuration, but it has not
  191. been tested in production like RabbitMQ has. If you have any problems with
  192. using STOMP and celery, please report the bugs to the issue tracker:
  193. http://github.com/ask/celery/issues/
  194. First you have to use the ``master`` branch of ``celery``::
  195. $ git clone git://github.com/ask/celery.git
  196. $ cd celery
  197. $ sudo python setup.py install
  198. $ cd ..
  199. Then you need to install the ``stompbackend`` branch of ``carrot``::
  200. $ git clone git://github.com/ask/carrot.git
  201. $ cd carrot
  202. $ git checkout stompbackend
  203. $ sudo python setup.py install
  204. $ cd ..
  205. And my fork of ``python-stomp`` which adds non-blocking support::
  206. $ hg clone http://bitbucket.org/asksol/python-stomp/
  207. $ cd python-stomp
  208. $ sudo python setup.py install
  209. $ cd ..
  210. In this example we will use a queue called ``celery`` which we created in
  211. the ActiveMQ web admin interface.
  212. **Note**: For ActiveMQ the queue name has to have ``"/queue/"`` prepended to
  213. it. i.e. the queue ``celery`` becomes ``/queue/celery``.
  214. Since a STOMP queue is a single named entity and it doesn't have the
  215. routing capabilities of AMQP you need to set both the ``queue``, and
  216. ``exchange`` settings to your queue name. This is a minor inconvenience since
  217. carrot needs to maintain the same interface for both AMQP and STOMP (obviously
  218. the one with the most capabilities won).
  219. Use the following specific settings in your ``settings.py``:
  220. .. code-block:: python
  221. # Makes python-stomp the default backend for carrot.
  222. CARROT_BACKEND = "stomp"
  223. # STOMP hostname and port settings.
  224. BROKER_HOST = "localhost"
  225. BROKER_PORT = 61613
  226. # The queue name to use (both queue and exchange must be set to the
  227. # same queue name when using STOMP)
  228. CELERY_DEFAULT_QUEUE = "/queue/celery"
  229. CELERY_DEFAULT_EXCHANGE = "/queue/celery"
  230. CELERY_QUEUES = {
  231. "/queue/celery": {"exchange": "/queue/celery"}
  232. }
  233. Now you can go on reading the tutorial in the README, ignoring any AMQP
  234. specific options.
  235. What features are not supported when using STOMP?
  236. --------------------------------------------------
  237. This is a (possible incomplete) list of features not available when
  238. using the STOMP backend:
  239. * routing keys
  240. * exchange types (direct, topic, headers, etc)
  241. * immediate
  242. * mandatory
  243. Features
  244. ========
  245. Can I send some tasks to only some servers?
  246. --------------------------------------------
  247. **Answer:** Yes. You can route tasks to an arbitrary server using AMQP,
  248. and a worker can bind to as many queues as it wants.
  249. Say you have two servers, ``x``, and ``y`` that handles regular tasks,
  250. and one server ``z``, that only handles feed related tasks, you can use this
  251. configuration:
  252. * Servers ``x`` and ``y``: settings.py:
  253. .. code-block:: python
  254. CELERY_DEFAULT_QUEUE = "regular_tasks"
  255. CELERY_QUEUES = {
  256. "regular_tasks": {
  257. "binding_key": "task.#",
  258. },
  259. }
  260. CELERY_DEFAULT_EXCHANGE = "tasks"
  261. CELERY_DEFAULT_EXCHANGE_TYPE = "topic"
  262. CELERY_DEFAULT_ROUTING_KEY = "task.regular"
  263. * Server ``z``: settings.py:
  264. .. code-block:: python
  265. CELERY_DEFAULT_QUEUE = "feed_tasks"
  266. CELERY_QUEUES = {
  267. "feed_tasks": {
  268. "binding_key": "feed.#",
  269. },
  270. }
  271. CELERY_DEFAULT_EXCHANGE = "tasks"
  272. CELERY_DEFAULT_ROUTING_KEY = "task.regular"
  273. CELERY_DEFAULT_EXCHANGE_TYPE = "topic"
  274. ``CELERY_QUEUES`` is a map of queue names and their exchange/type/binding_key,
  275. if you don't set exchange or exchange type, they will be taken from the
  276. ``CELERY_DEFAULT_EXCHANGE``/``CELERY_DEFAULT_EXCHANGE_TYPE`` settings.
  277. Now to make a Task run on the ``z`` server you need to set its
  278. ``routing_key`` attribute so it starts with the words ``"task.feed."``:
  279. .. code-block:: python
  280. from feedaggregator.models import Feed
  281. from celery.decorators import task
  282. @task(routing_key="feed.importer")
  283. def import_feed(feed_url):
  284. Feed.objects.import_feed(feed_url)
  285. or if subclassing the ``Task`` class directly:
  286. .. code-block:: python
  287. class FeedImportTask(Task):
  288. routing_key = "feed.importer"
  289. def run(self, feed_url):
  290. Feed.objects.import_feed(feed_url)
  291. You can also override this using the ``routing_key`` argument to
  292. :func:`celery.task.apply_async`:
  293. >>> from myapp.tasks import RefreshFeedTask
  294. >>> RefreshFeedTask.apply_async(args=["http://cnn.com/rss"],
  295. ... routing_key="feed.importer")
  296. If you want, you can even have your feed processing worker handle regular
  297. tasks as well, maybe in times when there's a lot of work to do.
  298. Just add a new queue to server ``z``'s ``CELERY_QUEUES``:
  299. .. code-block:: python
  300. CELERY_QUEUES = {
  301. "feed_tasks": {
  302. "binding_key": "feed.#",
  303. },
  304. "regular_tasks": {
  305. "binding_key": "task.#",
  306. },
  307. }
  308. Since the default exchange is ``tasks``, they will both use the same
  309. exchange.
  310. If you have another queue but on another exchange you want to add,
  311. just specify a custom exchange and exchange type:
  312. .. code-block:: python
  313. CELERY_QUEUES = {
  314. "feed_tasks": {
  315. "binding_key": "feed.#",
  316. },
  317. "regular_tasks": {
  318. "binding_key": "task.#",
  319. }
  320. "image_tasks": {
  321. "binding_key": "image.compress",
  322. "exchange": "mediatasks",
  323. "exchange_type": "direct",
  324. },
  325. }
  326. If you're confused about these terms, you should read up on AMQP and RabbitMQ.
  327. `Rabbits and Warrens`_ is an excellent blog post describing queues and
  328. exchanges. There's also AMQP in 10 minutes*: `Flexible Routing Model`_,
  329. and `Standard Exchange Types`_. For users of RabbitMQ the `RabbitMQ FAQ`_
  330. could also be useful as a source of information.
  331. .. _`Rabbits and Warrens`: http://blogs.digitar.com/jjww/2009/01/rabbits-and-warrens/
  332. .. _`Flexible Routing Model`: http://bit.ly/95XFO1
  333. .. _`Standard Exchange Types`: http://bit.ly/EEWca
  334. .. _`RabbitMQ FAQ`: http://www.rabbitmq.com/faq.html
  335. Can I use celery without Django?
  336. --------------------------------
  337. **Answer:** Yes.
  338. Celery uses something called loaders to read/setup configuration, import
  339. modules that register tasks and to decide what happens when a task is
  340. executed. Currently there are two loaders, the default loader and the Django
  341. loader. If you want to use celery without a Django project, you either have to
  342. use the default loader, or write a loader of your own.
  343. The rest of this answer describes how to use the default loader.
  344. While it is possible to use Celery from outside of Django, we still need
  345. Django itself to run, this is to use the ORM and cache-framework.
  346. Duplicating these features would be time consuming and mostly pointless, so
  347. while me might rewrite these in the future, this is a good solution in the
  348. mean time.
  349. Install Django using your favorite install tool, ``easy_install``, ``pip``, or
  350. whatever::
  351. # easy_install django # as root
  352. You need a configuration file named ``celeryconfig.py``, either in the
  353. directory you run ``celeryd`` in, or in a Python library path where it is
  354. able to find it. The configuration file can contain any of the settings
  355. described in :mod:`celery.conf`. In addition; if you're using the
  356. database backend you have to configure the database. Here is an example
  357. configuration using the database backend with MySQL:
  358. .. code-block:: python
  359. # Broker configuration
  360. BROKER_HOST = "localhost"
  361. BROKER_PORT = "5672"
  362. BROKER_VHOST = "celery"
  363. BROKER_USER = "celery"
  364. BROKER_PASSWORD = "celerysecret"
  365. CARROT_BACKEND="amqp"
  366. # Using the database backend.
  367. CELERY_BACKEND = "database"
  368. DATABASE_ENGINE = "mysql" # see Django docs for a description of these.
  369. DATABASE_NAME = "mydb"
  370. DATABASE_HOST = "mydb.example.org"
  371. DATABASE_USER = "myuser"
  372. DATABASE_PASSWORD = "mysecret"
  373. # Number of processes that processes tasks simultaneously.
  374. CELERYD_CONCURRENCY = 8
  375. # Modules to import when celeryd starts.
  376. # This must import every module where you register tasks so celeryd
  377. # is able to find and run them.
  378. CELERY_IMPORTS = ("mytaskmodule1", "mytaskmodule2")
  379. With this configuration file in the current directory you have to
  380. run ``celeryinit`` to create the database tables::
  381. $ celeryinit
  382. At this point you should be able to successfully run ``celeryd``::
  383. $ celeryd --loglevel=INFO
  384. and send a task from a python shell (note that it must be able to import
  385. ``celeryconfig.py``):
  386. >>> from celery.task.builtins import PingTask
  387. >>> result = PingTask.apply_async()
  388. >>> result.get()
  389. 'pong'
  390. The celery test-suite is failing
  391. --------------------------------
  392. **Answer**: If you're running tests from your Django project, and the celery
  393. test suite is failing in that context, then follow the steps below. If the
  394. celery tests are failing in another context, please report an issue to our
  395. issue tracker at GitHub:
  396. http://github.com/ask/celery/issues/
  397. That Django is running tests for all applications in ``INSTALLED_APPS``
  398. by default is a pet peeve for many. You should use a test runner that either
  399. 1) Explicitly lists the apps you want to run tests for, or
  400. 2) Make a test runner that skips tests for apps you don't want to run.
  401. For example the test runner that celery is using:
  402. http://bit.ly/NVKep
  403. To use this test runner, add the following to your ``settings.py``:
  404. .. code-block:: python
  405. TEST_RUNNER = "celery.tests.runners.run_tests"
  406. TEST_APPS = (
  407. "app1",
  408. "app2",
  409. "app3",
  410. "app4",
  411. )
  412. Or, if you just want to skip the celery tests:
  413. .. code-block:: python
  414. INSTALLED_APPS = (.....)
  415. TEST_RUNNER = "celery.tests.runners.run_tests"
  416. TEST_APPS = filter(lambda k: k != "celery", INSTALLED_APPS)
  417. Can I change the interval of a periodic task at runtime?
  418. --------------------------------------------------------
  419. **Answer**: Yes. You can override ``PeriodicTask.is_due`` or turn
  420. ``PeriodicTask.run_every`` into a property:
  421. .. code-block:: python
  422. class MyPeriodic(PeriodicTask):
  423. def run(self):
  424. # ...
  425. @property
  426. def run_every(self):
  427. return get_interval_from_database(...)
  428. Does celery support task priorities?
  429. ------------------------------------
  430. **Answer**: No. In theory, yes, as AMQP supports priorities. However
  431. RabbitMQ doesn't implement them yet.
  432. The usual way to prioritize work in celery, is to route high priority tasks
  433. to different servers. In the real world this may actually work better than per message
  434. priorities. You can use this in combination with rate limiting to achieve a
  435. highly performant system.
  436. Can I schedule tasks to execute at a specific time?
  437. ---------------------------------------------------
  438. .. module:: celery.task.base
  439. **Answer**: Yes. You can use the ``eta`` argument of :meth:`Task.apply_async`.
  440. However, you can't schedule a periodic task at a specific time yet.
  441. The good news is, if anyone is willing
  442. to implement it, it shouldn't be that hard. Some pointers to achieve this has
  443. been written here: http://bit.ly/99UQNO
  444. How do I shut down ``celeryd`` safely?
  445. --------------------------------------
  446. **Answer**: Use the ``TERM`` signal, and celery will finish all currently
  447. executing jobs and shut down as soon as possible. No tasks should be lost.
  448. You should never stop ``celeryd`` with the ``KILL`` signal (``-9``),
  449. unless you've tried ``TERM`` a few times and waited a few minutes to let it
  450. get a chance to shut down.