FAQ 20 KB

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