FAQ 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690
  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. Celery does not depend on Django anymore. To use Celery with Django you have
  41. to use the `django-celery`_ package:
  42. .. _`django-celery`: http://pypi.python.org/pypi/django-celery
  43. Do I have to use AMQP/RabbitMQ?
  44. -------------------------------
  45. **Answer**: No.
  46. You can also use Redis or an SQL database, see `Using other
  47. queues`_.
  48. .. _`Using other queues`:
  49. http://ask.github.com/celery/tutorials/otherqueues.html
  50. Redis or a database won't perform as well as
  51. an AMQP broker. If you have strict reliability requirements you are
  52. encouraged to use RabbitMQ or another AMQP broker. Redis/database also use
  53. polling, so they are likely to consume more resources. However, if you for
  54. some reason are not able to use AMQP, feel free to use these alternatives.
  55. They will probably work fine for most use cases, and note that the above
  56. points are not specific to celery; If using Redis/database as a queue worked
  57. fine for you before, it probably will now. You can always upgrade later
  58. if you need to.
  59. Is celery multi-lingual?
  60. ------------------------
  61. **Answer:** Yes.
  62. celeryd is an implementation of celery in python. If the language has an AMQP
  63. client, there shouldn't be much work to create a worker in your language.
  64. A celery worker is just a program connecting to the broker to consume
  65. messages. There's no other communication involved.
  66. Also, there's another way to be language indepedent, and that is to use REST
  67. tasks, instead of your tasks being functions, they're URLs. With this
  68. information you can even create simple web servers that enable preloading of
  69. code. See: `User Guide: Remote Tasks`_.
  70. .. _`User Guide: Remote Tasks`:
  71. http://ask.github.com/celery/userguide/remote-tasks.html
  72. Troubleshooting
  73. ===============
  74. MySQL is throwing deadlock errors, what can I do?
  75. -------------------------------------------------
  76. **Answer:** MySQL has default isolation level set to ``REPEATABLE-READ``,
  77. if you don't really need that, set it to ``READ-COMMITTED``.
  78. You can do that by adding the following to your ``my.cnf``::
  79. [mysqld]
  80. transaction-isolation = READ-COMMITTED
  81. For more information about InnoDBs transaction model see `MySQL - The InnoDB
  82. Transaction Model and Locking`_ in the MySQL user manual.
  83. (Thanks to Honza Kral and Anton Tsigularov for this solution)
  84. .. _`MySQL - The InnoDB Transaction Model and Locking`: http://dev.mysql.com/doc/refman/5.1/en/innodb-transaction-model.html
  85. celeryd is not doing anything, just hanging
  86. --------------------------------------------
  87. **Answer:** See `MySQL is throwing deadlock errors, what can I do?`_.
  88. or `Why is Task.delay/apply\* just hanging?`.
  89. Why is Task.delay/apply\*/celeryd just hanging?
  90. -----------------------------------------------
  91. **Answer:** There is a bug in some AMQP clients that will make it hang if
  92. it's not able to authenticate the current user, the password doesn't match or
  93. the user does not have access to the virtual host specified. Be sure to check
  94. your broker logs (for RabbitMQ that is ``/var/log/rabbitmq/rabbit.log`` on
  95. most systems), it usually contains a message describing the reason.
  96. Why won't celeryd run on FreeBSD?
  97. ---------------------------------
  98. **Answer:** multiprocessing.Pool requires a working POSIX semaphore
  99. implementation which isn't enabled in FreeBSD by default. You have to enable
  100. POSIX semaphores in the kernel and manually recompile multiprocessing.
  101. Luckily, Viktor Petersson has written a tutorial to get you started with
  102. Celery on FreeBSD here:
  103. http://www.playingwithwire.com/2009/10/how-to-get-celeryd-to-work-on-freebsd/
  104. I'm having ``IntegrityError: Duplicate Key`` errors. Why?
  105. ---------------------------------------------------------
  106. **Answer:** See `MySQL is throwing deadlock errors, what can I do?`_.
  107. Thanks to howsthedotcom.
  108. Why aren't my tasks processed?
  109. ------------------------------
  110. **Answer:** With RabbitMQ you can see how many consumers are currently
  111. receiving tasks by running the following command::
  112. $ rabbitmqctl list_queues -p <myvhost> name messages consumers
  113. Listing queues ...
  114. celery 2891 2
  115. This shows that there's 2891 messages waiting to be processed in the task
  116. queue, and there are two consumers processing them.
  117. One reason that the queue is never emptied could be that you have a stale
  118. celery process taking the messages hostage. This could happen if celeryd
  119. wasn't properly shut down.
  120. When a message is recieved by a worker the broker waits for it to be
  121. acknowledged before marking the message as processed. The broker will not
  122. re-send that message to another consumer until the consumer is shut down
  123. properly.
  124. If you hit this problem you have to kill all workers manually and restart
  125. them::
  126. ps auxww | grep celeryd | awk '{print $2}' | xargs kill
  127. You might have to wait a while until all workers have finished the work they're
  128. doing. If it's still hanging after a long time you can kill them by force
  129. with::
  130. ps auxww | grep celeryd | awk '{print $2}' | xargs kill -9
  131. Why won't my Task run?
  132. ----------------------
  133. **Answer:** There might be syntax errors preventing the tasks module being imported.
  134. You can find out if celery is able to run the task by executing the
  135. task manually:
  136. >>> from myapp.tasks import MyPeriodicTask
  137. >>> MyPeriodicTask.delay()
  138. Watch celeryds logfile to see if it's able to find the task, or if some
  139. other error is happening.
  140. Why won't my Periodic Task run?
  141. -------------------------------
  142. **Answer:** See `Why won't my Task run?`_.
  143. How do I discard all waiting tasks?
  144. ------------------------------------
  145. **Answer:** Use ``celery.task.discard_all()``, like this:
  146. >>> from celery.task import discard_all
  147. >>> discard_all()
  148. 1753
  149. The number ``1753`` is the number of messages deleted.
  150. You can also start celeryd with the ``--discard`` argument which will
  151. accomplish the same thing.
  152. I've discarded messages, but there are still messages left in the queue?
  153. ------------------------------------------------------------------------
  154. **Answer:** Tasks are acknowledged (removed from the queue) as soon
  155. as they are actually executed. After the worker has received a task, it will
  156. take some time until it is actually executed, especially if there are a lot
  157. of tasks already waiting for execution. Messages that are not acknowledged are
  158. hold on to by the worker until it closes the connection to the broker (AMQP
  159. server). When that connection is closed (e.g because the worker was stopped)
  160. the tasks will be re-sent by the broker to the next available worker (or the
  161. same worker when it has been restarted), so to properly purge the queue of
  162. waiting tasks you have to stop all the workers, and then discard the tasks
  163. using ``discard_all``.
  164. Windows: The ``-B`` / ``--beat`` option to celeryd doesn't work?
  165. ----------------------------------------------------------------
  166. **Answer**: That's right. Run ``celerybeat`` and ``celeryd`` as separate
  167. services instead.
  168. Tasks
  169. =====
  170. How can I reuse the same connection when applying tasks?
  171. --------------------------------------------------------
  172. **Answer**: See :doc:`userguide/executing`.
  173. Can I execute a task by name?
  174. -----------------------------
  175. **Answer**: Yes. Use :func:`celery.execute.send_task`.
  176. You can also execute a task by name from any language
  177. that has an AMQP client.
  178. >>> from celery.execute import send_task
  179. >>> send_task("tasks.add", args=[2, 2], kwargs={})
  180. <AsyncResult: 373550e8-b9a0-4666-bc61-ace01fa4f91d>
  181. Results
  182. =======
  183. How dow I get the result of a task if I have the ID that points there?
  184. ----------------------------------------------------------------------
  185. **Answer**: Use ``Task.AsyncResult``::
  186. >>> result = MyTask.AsyncResult(task_id)
  187. >>> result.get()
  188. This will give you a :class:`celery.result.BaseAsyncResult` instance
  189. using the tasks current result backend.
  190. If you need to specify a custom result backend you should use
  191. :class:`celery.result.BaseAsyncResult` directly::
  192. >>> from celery.result import BaseAsyncResult
  193. >>> result = BaseAsyncResult(task_id, backend=...)
  194. >>> result.get()
  195. Brokers
  196. =======
  197. Why is RabbitMQ crashing?
  198. -------------------------
  199. RabbitMQ will crash if it runs out of memory. This will be fixed in a
  200. future release of RabbitMQ. please refer to the RabbitMQ FAQ:
  201. http://www.rabbitmq.com/faq.html#node-runs-out-of-memory
  202. Some common Celery misconfigurations can crash RabbitMQ:
  203. * Events.
  204. Running ``celeryd`` with the ``-E``/``--events`` option will send messages
  205. for events happening inside of the worker. If these event messages
  206. are not consumed, you will eventually run out of memory.
  207. Events should only be enabled if you have an active monitor consuming them.
  208. * AMQP backend results.
  209. When running with the AMQP result backend, every task result will be sent
  210. as a message. If you don't collect these results, they will build up and
  211. RabbitMQ will eventually run out of memory.
  212. If you don't use the results for a task, make sure you set the
  213. ``ignore_result`` option:
  214. .. code-block python
  215. @task(ignore_result=True)
  216. def mytask():
  217. ...
  218. class MyTask(Task):
  219. ignore_result = True
  220. Results can also be disabled globally using the ``CELERY_IGNORE_RESULT``
  221. setting.
  222. Can I use celery with ActiveMQ/STOMP?
  223. -------------------------------------
  224. **Answer**: Yes, but this is somewhat experimental for now.
  225. It is working ok in a test configuration, but it has not
  226. been tested in production like RabbitMQ has. If you have any problems with
  227. using STOMP and celery, please report the bugs to the issue tracker:
  228. http://github.com/ask/celery/issues/
  229. First you have to use the ``master`` branch of ``celery``::
  230. $ git clone git://github.com/ask/celery.git
  231. $ cd celery
  232. $ sudo python setup.py install
  233. $ cd ..
  234. Then you need to install the ``stompbackend`` branch of ``carrot``::
  235. $ git clone git://github.com/ask/carrot.git
  236. $ cd carrot
  237. $ git checkout stompbackend
  238. $ sudo python setup.py install
  239. $ cd ..
  240. And my fork of ``python-stomp`` which adds non-blocking support::
  241. $ hg clone http://bitbucket.org/asksol/python-stomp/
  242. $ cd python-stomp
  243. $ sudo python setup.py install
  244. $ cd ..
  245. In this example we will use a queue called ``celery`` which we created in
  246. the ActiveMQ web admin interface.
  247. **Note**: For ActiveMQ the queue name has to have ``"/queue/"`` prepended to
  248. it. i.e. the queue ``celery`` becomes ``/queue/celery``.
  249. Since a STOMP queue is a single named entity and it doesn't have the
  250. routing capabilities of AMQP you need to set both the ``queue``, and
  251. ``exchange`` settings to your queue name. This is a minor inconvenience since
  252. carrot needs to maintain the same interface for both AMQP and STOMP (obviously
  253. the one with the most capabilities won).
  254. Use the following specific settings in your ``settings.py``:
  255. .. code-block:: python
  256. # Makes python-stomp the default backend for carrot.
  257. CARROT_BACKEND = "stomp"
  258. # STOMP hostname and port settings.
  259. BROKER_HOST = "localhost"
  260. BROKER_PORT = 61613
  261. # The queue name to use (both queue and exchange must be set to the
  262. # same queue name when using STOMP)
  263. CELERY_DEFAULT_QUEUE = "/queue/celery"
  264. CELERY_DEFAULT_EXCHANGE = "/queue/celery"
  265. CELERY_QUEUES = {
  266. "/queue/celery": {"exchange": "/queue/celery"}
  267. }
  268. Now you can go on reading the tutorial in the README, ignoring any AMQP
  269. specific options.
  270. What features are not supported when using STOMP?
  271. --------------------------------------------------
  272. This is a (possible incomplete) list of features not available when
  273. using the STOMP backend:
  274. * routing keys
  275. * exchange types (direct, topic, headers, etc)
  276. * immediate
  277. * mandatory
  278. Features
  279. ========
  280. How can I run a task once another task has finished?
  281. ----------------------------------------------------
  282. **Answer**: You can safely launch a task inside a task.
  283. Also, a common pattern is to use callback tasks:
  284. .. code-block:: python
  285. @task()
  286. def add(x, y, callback=None):
  287. result = x + y
  288. if callback:
  289. callback.delay(result)
  290. return result
  291. @task(ignore_result=True)
  292. def log_result(result, **kwargs):
  293. logger = log_result.get_logger(**kwargs)
  294. logger.info("log_result got: %s" % (result, ))
  295. >>> add.delay(2, 2, callback=log_result)
  296. Can I cancel the execution of a task?
  297. -------------------------------------
  298. **Answer**: Yes. Use ``result.revoke``::
  299. >>> result = add.apply_async(args=[2, 2], countdown=120)
  300. >>> result.revoke()
  301. or if you only have the task id::
  302. >>> from celery.task.control import revoke
  303. >>> revoke(task_id)
  304. Why aren't my remote control commands received by all workers?
  305. --------------------------------------------------------------
  306. **Answer**: To receive broadcast remote control commands, every ``celeryd``
  307. uses its hostname to create a unique queue name to listen to,
  308. so if you have more than one worker with the same hostname, the
  309. control commands will be recieved in round-robin between them.
  310. To work around this you can explicitly set the hostname for every worker
  311. using the ``--hostname`` argument to ``celeryd``::
  312. $ celeryd --hostname=$(hostname).1
  313. $ celeryd --hostname=$(hostname).2
  314. etc, etc.
  315. Can I send some tasks to only some servers?
  316. --------------------------------------------
  317. **Answer:** Yes. You can route tasks to an arbitrary server using AMQP,
  318. and a worker can bind to as many queues as it wants.
  319. Say you have two servers, ``x``, and ``y`` that handles regular tasks,
  320. and one server ``z``, that only handles feed related tasks, you can use this
  321. configuration:
  322. * Servers ``x`` and ``y``: settings.py:
  323. .. code-block:: python
  324. CELERY_DEFAULT_QUEUE = "regular_tasks"
  325. CELERY_QUEUES = {
  326. "regular_tasks": {
  327. "binding_key": "task.#",
  328. },
  329. }
  330. CELERY_DEFAULT_EXCHANGE = "tasks"
  331. CELERY_DEFAULT_EXCHANGE_TYPE = "topic"
  332. CELERY_DEFAULT_ROUTING_KEY = "task.regular"
  333. * Server ``z``: settings.py:
  334. .. code-block:: python
  335. CELERY_DEFAULT_QUEUE = "feed_tasks"
  336. CELERY_QUEUES = {
  337. "feed_tasks": {
  338. "binding_key": "feed.#",
  339. },
  340. }
  341. CELERY_DEFAULT_EXCHANGE = "tasks"
  342. CELERY_DEFAULT_ROUTING_KEY = "task.regular"
  343. CELERY_DEFAULT_EXCHANGE_TYPE = "topic"
  344. ``CELERY_QUEUES`` is a map of queue names and their exchange/type/binding_key,
  345. if you don't set exchange or exchange type, they will be taken from the
  346. ``CELERY_DEFAULT_EXCHANGE``/``CELERY_DEFAULT_EXCHANGE_TYPE`` settings.
  347. Now to make a Task run on the ``z`` server you need to set its
  348. ``routing_key`` attribute so it starts with the words ``"task.feed."``:
  349. .. code-block:: python
  350. from feedaggregator.models import Feed
  351. from celery.decorators import task
  352. @task(routing_key="feed.importer")
  353. def import_feed(feed_url):
  354. Feed.objects.import_feed(feed_url)
  355. or if subclassing the ``Task`` class directly:
  356. .. code-block:: python
  357. class FeedImportTask(Task):
  358. routing_key = "feed.importer"
  359. def run(self, feed_url):
  360. Feed.objects.import_feed(feed_url)
  361. You can also override this using the ``routing_key`` argument to
  362. :func:`celery.task.apply_async`:
  363. >>> from myapp.tasks import RefreshFeedTask
  364. >>> RefreshFeedTask.apply_async(args=["http://cnn.com/rss"],
  365. ... routing_key="feed.importer")
  366. If you want, you can even have your feed processing worker handle regular
  367. tasks as well, maybe in times when there's a lot of work to do.
  368. Just add a new queue to server ``z``'s ``CELERY_QUEUES``:
  369. .. code-block:: python
  370. CELERY_QUEUES = {
  371. "feed_tasks": {
  372. "binding_key": "feed.#",
  373. },
  374. "regular_tasks": {
  375. "binding_key": "task.#",
  376. },
  377. }
  378. Since the default exchange is ``tasks``, they will both use the same
  379. exchange.
  380. If you have another queue but on another exchange you want to add,
  381. just specify a custom exchange and exchange type:
  382. .. code-block:: python
  383. CELERY_QUEUES = {
  384. "feed_tasks": {
  385. "binding_key": "feed.#",
  386. },
  387. "regular_tasks": {
  388. "binding_key": "task.#",
  389. }
  390. "image_tasks": {
  391. "binding_key": "image.compress",
  392. "exchange": "mediatasks",
  393. "exchange_type": "direct",
  394. },
  395. }
  396. If you're confused about these terms, you should read up on AMQP and RabbitMQ.
  397. `Rabbits and Warrens`_ is an excellent blog post describing queues and
  398. exchanges. There's also AMQP in 10 minutes*: `Flexible Routing Model`_,
  399. and `Standard Exchange Types`_. For users of RabbitMQ the `RabbitMQ FAQ`_
  400. could also be useful as a source of information.
  401. .. _`Rabbits and Warrens`: http://blogs.digitar.com/jjww/2009/01/rabbits-and-warrens/
  402. .. _`Flexible Routing Model`: http://bit.ly/95XFO1
  403. .. _`Standard Exchange Types`: http://bit.ly/EEWca
  404. .. _`RabbitMQ FAQ`: http://www.rabbitmq.com/faq.html
  405. Can I change the interval of a periodic task at runtime?
  406. --------------------------------------------------------
  407. **Answer**: Yes. You can override ``PeriodicTask.is_due`` or turn
  408. ``PeriodicTask.run_every`` into a property:
  409. .. code-block:: python
  410. class MyPeriodic(PeriodicTask):
  411. def run(self):
  412. # ...
  413. @property
  414. def run_every(self):
  415. return get_interval_from_database(...)
  416. Does celery support task priorities?
  417. ------------------------------------
  418. **Answer**: No. In theory, yes, as AMQP supports priorities. However
  419. RabbitMQ doesn't implement them yet.
  420. The usual way to prioritize work in celery, is to route high priority tasks
  421. to different servers. In the real world this may actually work better than per message
  422. priorities. You can use this in combination with rate limiting to achieve a
  423. highly performant system.
  424. Should I use retry or acks_late?
  425. --------------------------------
  426. **Answer**: Depends. It's not necessarily one or the other, you may want
  427. to use both.
  428. ``Task.retry`` is used to retry tasks, notably for expected errors that
  429. is catchable with the ``try:`` block. The AMQP transaction is not used
  430. for these errors: **if the task raises an exception it is still acked!**.
  431. The ``acks_late`` setting would be used when you need the task to be
  432. executed again if the worker (for some reason) crashes mid-execution.
  433. It's important to note that the worker is not known to crash, and if
  434. it does it is usually an unrecoverable error that requires human
  435. intervention (bug in the worker, or task code).
  436. In an ideal world you could safely retry any task that has failed, but
  437. this is rarely the case. Imagine the following task:
  438. .. code-block:: python
  439. @task()
  440. def process_upload(filename, tmpfile):
  441. # Increment a file count stored in a database
  442. increment_file_counter()
  443. add_file_metadata_to_db(filename, tmpfile)
  444. copy_file_to_destination(filename, tmpfile)
  445. If this crashed in the middle of copying the file to its destination
  446. the world would contain incomplete state. This is not a critical
  447. scenario of course, but you can probably imagine something far more
  448. sinister. So for ease of programming we have less reliability;
  449. It's a good default, users who require it and know what they
  450. are doing can still enable acks_late (and in the future hopefully
  451. use manual acknowledgement)
  452. In addition ``Task.retry`` has features not available in AMQP
  453. transactions: delay between retries, max retries, etc.
  454. So use retry for Python errors, and if your task is reentrant
  455. combine that with ``acks_late`` if that level of reliability
  456. is required.
  457. Can I schedule tasks to execute at a specific time?
  458. ---------------------------------------------------
  459. .. module:: celery.task.base
  460. **Answer**: Yes. You can use the ``eta`` argument of :meth:`Task.apply_async`.
  461. Or to schedule a periodic task at a specific time, use the
  462. :class:`celery.task.schedules.crontab` schedule behavior:
  463. .. code-block:: python
  464. from celery.task.schedules import crontab
  465. from celery.decorators import periodic_task
  466. @periodic_task(run_every=crontab(hours=7, minute=30, day_of_week="mon"))
  467. def every_monday_morning():
  468. print("This is run every monday morning at 7:30")
  469. How do I shut down ``celeryd`` safely?
  470. --------------------------------------
  471. **Answer**: Use the ``TERM`` signal, and celery will finish all currently
  472. executing jobs and shut down as soon as possible. No tasks should be lost.
  473. You should never stop ``celeryd`` with the ``KILL`` signal (``-9``),
  474. unless you've tried ``TERM`` a few times and waited a few minutes to let it
  475. get a chance to shut down. As if you do tasks may be terminated mid-execution,
  476. and they will not be re-run unless you have the ``acks_late`` option set.
  477. (``Task.acks_late`` / ``CELERY_ACKS_LATE``).
  478. How do I run celeryd in the background on [platform]?
  479. -----------------------------------------------------
  480. **Answer**: Please see :doc:`cookbook/daemonizing`.