FAQ 22 KB

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