faq.rst 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893
  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 performance 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-loc:
  33. Does Celery really consist of 50.000 lines of code?
  34. ---------------------------------------------------
  35. **Answer:** No, this and similarly large numbers have
  36. been reported at various locations.
  37. The numbers as of this writing are:
  38. - core: 7,141 lines of code.
  39. - tests: 14,209 lines.
  40. - backends, contrib, compat utilities: 9,032 lines.
  41. Lines of code is not a useful metric, so
  42. even if Celery did consist of 50k lines of code you would not
  43. be able to draw any conclusions from such a number.
  44. Does Celery have many dependencies?
  45. -----------------------------------
  46. A common criticism is that Celery uses too many dependencies.
  47. The rationale behind such a fear is hard to imagine, especially considering
  48. code reuse as the established way to combat complexity in modern software
  49. development, and that the cost of adding dependencies is very low now
  50. that package managers like pip and PyPI makes the hassle of installing
  51. and maintaining dependencies a thing of the past.
  52. Celery has replaced several dependencies along the way, and
  53. the current list of dependencies are:
  54. celery
  55. ~~~~~~
  56. - `kombu`_
  57. Kombu is part of the Celery ecosystem and is the library used
  58. to send and receive messages. It is also the library that enables
  59. us to support many different message brokers. It is also used by the
  60. OpenStack project, and many others, validating the choice to separate
  61. it from the Celery codebase.
  62. .. _`kombu`: http://pypi.python.org/pypi/kombu
  63. - `billiard`_
  64. Billiard is a fork of the Python multiprocessing module containing
  65. many performance and stability improvements. It is an eventual goal
  66. that these improvements will be merged back into Python one day.
  67. It is also used for compatibility with older Python versions
  68. that doesn't come with the multiprocessing module.
  69. .. _`billiard`: http://pypi.python.org/pypi/billiard
  70. - `pytz`
  71. The pytz module provides timezone definitions and related tools.
  72. .. _`pytz`: http://pypi.python.org/pypi/pytz
  73. django-celery
  74. ~~~~~~~~~~~~~
  75. If you use django-celery then you don't have to install celery separately,
  76. as it will make sure that the required version is installed.
  77. django-celery does not have any other dependencies.
  78. kombu
  79. ~~~~~
  80. Kombu depends on the following packages:
  81. - `amqp`_
  82. The underlying pure-Python amqp client implementation. AMQP being the default
  83. broker this is a natural dependency.
  84. .. _`amqp`: http://pypi.python.org/pypi/amqp
  85. - `anyjson`_
  86. anyjson is an utility library to select the best possible
  87. JSON implementation.
  88. .. _`anyjson`: http://pypi.python.org/pypi/anyjson
  89. .. note::
  90. For compatibility reasons additional packages may be installed
  91. if you are running on older Python versions,
  92. for example Python 2.6 depends on the ``importlib``,
  93. and ``ordereddict`` libraries.
  94. Also, to handle the dependencies for popular configuration
  95. choices Celery defines a number of "bundle" packages,
  96. see :ref:`bundles`.
  97. .. _faq-heavyweight:
  98. Is Celery heavy-weight?
  99. -----------------------
  100. Celery poses very little overhead both in memory footprint and
  101. performance.
  102. But please note that the default configuration is not optimized for time nor
  103. space, see the :ref:`guide-optimizing` guide for more information.
  104. .. _faq-serializion-is-a-choice:
  105. Is Celery dependent on pickle?
  106. ------------------------------
  107. **Answer:** No.
  108. Celery can support any serialization scheme and has built-in support for
  109. JSON, YAML, Pickle and msgpack. Also, as every task is associated with a
  110. content type, you can even send one task using pickle, and another using JSON.
  111. The default serialization format is pickle simply because it is
  112. convenient (it supports sending complex Python objects as task arguments).
  113. If you need to communicate with other languages you should change
  114. to a serialization format that is suitable for that.
  115. You can set a global default serializer, the default serializer for a
  116. particular Task, or even what serializer to use when sending a single task
  117. instance.
  118. .. _faq-is-celery-for-django-only:
  119. Is Celery for Django only?
  120. --------------------------
  121. **Answer:** No.
  122. You can use Celery with any framework, web or otherwise.
  123. .. _faq-is-celery-for-rabbitmq-only:
  124. Do I have to use AMQP/RabbitMQ?
  125. -------------------------------
  126. **Answer**: No.
  127. You can also use Redis, Beanstalk, CouchDB, MongoDB or an SQL database,
  128. see :ref:`brokers`.
  129. These "virtual transports" may have limited broadcast and event functionality.
  130. For example remote control commands only works with AMQP and Redis.
  131. Redis or a database won't perform as well as
  132. an AMQP broker. If you have strict reliability requirements you are
  133. encouraged to use RabbitMQ or another AMQP broker. Redis/database also use
  134. polling, so they are likely to consume more resources. However, if you for
  135. some reason are not able to use AMQP, feel free to use these alternatives.
  136. They will probably work fine for most use cases, and note that the above
  137. points are not specific to Celery; If using Redis/database as a queue worked
  138. fine for you before, it probably will now. You can always upgrade later
  139. if you need to.
  140. .. _faq-is-celery-multilingual:
  141. Is Celery multilingual?
  142. ------------------------
  143. **Answer:** Yes.
  144. :mod:`~celery.bin.worker` is an implementation of Celery in Python. If the
  145. language has an AMQP client, there shouldn't be much work to create a worker
  146. in your language. A Celery worker is just a program connecting to the broker
  147. to process messages.
  148. Also, there's another way to be language independent, and that is to use REST
  149. tasks, instead of your tasks being functions, they're URLs. With this
  150. information you can even create simple web servers that enable preloading of
  151. code. See: :ref:`User Guide: Remote Tasks <guide-webhooks>`.
  152. .. _faq-troubleshooting:
  153. Troubleshooting
  154. ===============
  155. .. _faq-mysql-deadlocks:
  156. MySQL is throwing deadlock errors, what can I do?
  157. -------------------------------------------------
  158. **Answer:** MySQL has default isolation level set to `REPEATABLE-READ`,
  159. if you don't really need that, set it to `READ-COMMITTED`.
  160. You can do that by adding the following to your :file:`my.cnf`::
  161. [mysqld]
  162. transaction-isolation = READ-COMMITTED
  163. For more information about InnoDB`s transaction model see `MySQL - The InnoDB
  164. Transaction Model and Locking`_ in the MySQL user manual.
  165. (Thanks to Honza Kral and Anton Tsigularov for this solution)
  166. .. _`MySQL - The InnoDB Transaction Model and Locking`: http://dev.mysql.com/doc/refman/5.1/en/innodb-transaction-model.html
  167. .. _faq-worker-hanging:
  168. The worker is not doing anything, just hanging
  169. ----------------------------------------------
  170. **Answer:** See `MySQL is throwing deadlock errors, what can I do?`_.
  171. or `Why is Task.delay/apply\* just hanging?`.
  172. .. _faq-results-unreliable:
  173. Task results aren't reliably returning
  174. --------------------------------------
  175. **Answer:** If you're using the database backend for results, and in particular
  176. using MySQL, see `MySQL is throwing deadlock errors, what can I do?`_.
  177. .. _faq-publish-hanging:
  178. Why is Task.delay/apply\*/the worker just hanging?
  179. --------------------------------------------------
  180. **Answer:** There is a bug in some AMQP clients that will make it hang if
  181. it's not able to authenticate the current user, the password doesn't match or
  182. the user does not have access to the virtual host specified. Be sure to check
  183. your broker logs (for RabbitMQ that is :file:`/var/log/rabbitmq/rabbit.log` on
  184. most systems), it usually contains a message describing the reason.
  185. .. _faq-worker-on-freebsd:
  186. Does it work on FreeBSD?
  187. ------------------------
  188. **Answer:** The multiprocessing pool requires a working POSIX semaphore
  189. implementation which isn't enabled in FreeBSD by default. You have to enable
  190. POSIX semaphores in the kernel and manually recompile multiprocessing.
  191. Luckily, Viktor Petersson has written a tutorial to get you started with
  192. Celery on FreeBSD here:
  193. http://www.playingwithwire.com/2009/10/how-to-get-celeryd-to-work-on-freebsd/
  194. .. _faq-duplicate-key-errors:
  195. I'm having `IntegrityError: Duplicate Key` errors. Why?
  196. ---------------------------------------------------------
  197. **Answer:** See `MySQL is throwing deadlock errors, what can I do?`_.
  198. Thanks to howsthedotcom.
  199. .. _faq-worker-stops-processing:
  200. Why aren't my tasks processed?
  201. ------------------------------
  202. **Answer:** With RabbitMQ you can see how many consumers are currently
  203. receiving tasks by running the following command:
  204. .. code-block:: bash
  205. $ rabbitmqctl list_queues -p <myvhost> name messages consumers
  206. Listing queues ...
  207. celery 2891 2
  208. This shows that there's 2891 messages waiting to be processed in the task
  209. queue, and there are two consumers processing them.
  210. One reason that the queue is never emptied could be that you have a stale
  211. worker process taking the messages hostage. This could happen if the worker
  212. wasn't properly shut down.
  213. When a message is received by a worker the broker waits for it to be
  214. acknowledged before marking the message as processed. The broker will not
  215. re-send that message to another consumer until the consumer is shut down
  216. properly.
  217. If you hit this problem you have to kill all workers manually and restart
  218. them::
  219. ps auxww | grep celeryd | awk '{print $2}' | xargs kill
  220. You might have to wait a while until all workers have finished the work they're
  221. doing. If it's still hanging after a long time you can kill them by force
  222. with::
  223. ps auxww | grep celeryd | awk '{print $2}' | xargs kill -9
  224. .. _faq-task-does-not-run:
  225. Why won't my Task run?
  226. ----------------------
  227. **Answer:** There might be syntax errors preventing the tasks module being imported.
  228. You can find out if Celery is able to run the task by executing the
  229. task manually:
  230. >>> from myapp.tasks import MyPeriodicTask
  231. >>> MyPeriodicTask.delay()
  232. Watch the workers log file to see if it's able to find the task, or if some
  233. other error is happening.
  234. .. _faq-periodic-task-does-not-run:
  235. Why won't my periodic task run?
  236. -------------------------------
  237. **Answer:** See `Why won't my Task run?`_.
  238. .. _faq-purge-the-queue:
  239. How do I purge all waiting tasks?
  240. ---------------------------------
  241. **Answer:** You can use the ``celery purge`` command to purge
  242. all configured task queues:
  243. .. code-block:: bash
  244. $ celery purge
  245. or programatically:
  246. .. code-block:: python
  247. >>> from celery import current_app as celery
  248. >>> celery.control.purge()
  249. 1753
  250. If you only want to purge messages from a specific queue
  251. you have to use the AMQP API or the :program:`celery amqp` utility:
  252. .. code-block:: bash
  253. $ celery amqp queue.purge <queue name>
  254. The number 1753 is the number of messages deleted.
  255. You can also start :mod:`~celery.bin.worker` with the
  256. :option:`--purge` argument, to purge messages when the worker starts.
  257. .. _faq-messages-left-after-purge:
  258. I've purged messages, but there are still messages left in the queue?
  259. ---------------------------------------------------------------------
  260. **Answer:** Tasks are acknowledged (removed from the queue) as soon
  261. as they are actually executed. After the worker has received a task, it will
  262. take some time until it is actually executed, especially if there are a lot
  263. of tasks already waiting for execution. Messages that are not acknowledged are
  264. held on to by the worker until it closes the connection to the broker (AMQP
  265. server). When that connection is closed (e.g. because the worker was stopped)
  266. the tasks will be re-sent by the broker to the next available worker (or the
  267. same worker when it has been restarted), so to properly purge the queue of
  268. waiting tasks you have to stop all the workers, and then purge the tasks
  269. using :func:`celery.control.purge`.
  270. .. _faq-results:
  271. Results
  272. =======
  273. .. _faq-get-result-by-task-id:
  274. How do I get the result of a task if I have the ID that points there?
  275. ----------------------------------------------------------------------
  276. **Answer**: Use `task.AsyncResult`::
  277. >>> result = my_task.AsyncResult(task_id)
  278. >>> result.get()
  279. This will give you a :class:`~celery.result.AsyncResult` instance
  280. using the tasks current result backend.
  281. If you need to specify a custom result backend, or you want to use
  282. the current application's default backend you can use
  283. :class:`@Celery.AsyncResult`:
  284. >>> result = app.AsyncResult(task_id)
  285. >>> result.get()
  286. .. _faq-security:
  287. Security
  288. ========
  289. Isn't using `pickle` a security concern?
  290. ----------------------------------------
  291. **Answer**: Yes, indeed it is.
  292. You are right to have a security concern, as this can indeed be a real issue.
  293. It is essential that you protect against unauthorized
  294. access to your broker, databases and other services transmitting pickled
  295. data.
  296. For the task messages you can set the :setting:`CELERY_TASK_SERIALIZER`
  297. setting to "json" or "yaml" instead of pickle. There is
  298. currently no alternative solution for task results (but writing a
  299. custom result backend using JSON is a simple task)
  300. Note that this is not just something you should be aware of with Celery, for
  301. example also Django uses pickle for its cache client.
  302. Can messages be encrypted?
  303. --------------------------
  304. **Answer**: Some AMQP brokers supports using SSL (including RabbitMQ).
  305. You can enable this using the :setting:`BROKER_USE_SSL` setting.
  306. It is also possible to add additional encryption and security to messages,
  307. if you have a need for this then you should contact the :ref:`mailing-list`.
  308. Is it safe to run :program:`celery worker` as root?
  309. ---------------------------------------------------
  310. **Answer**: No!
  311. We're not currently aware of any security issues, but it would
  312. be incredibly naive to assume that they don't exist, so running
  313. the Celery services (:program:`celery worker`, :program:`celery beat`,
  314. :program:`celeryev`, etc) as an unprivileged user is recommended.
  315. .. _faq-brokers:
  316. Brokers
  317. =======
  318. Why is RabbitMQ crashing?
  319. -------------------------
  320. **Answer:** RabbitMQ will crash if it runs out of memory. This will be fixed in a
  321. future release of RabbitMQ. please refer to the RabbitMQ FAQ:
  322. http://www.rabbitmq.com/faq.html#node-runs-out-of-memory
  323. .. note::
  324. This is no longer the case, RabbitMQ versions 2.0 and above
  325. includes a new persister, that is tolerant to out of memory
  326. errors. RabbitMQ 2.1 or higher is recommended for Celery.
  327. If you're still running an older version of RabbitMQ and experience
  328. crashes, then please upgrade!
  329. Misconfiguration of Celery can eventually lead to a crash
  330. on older version of RabbitMQ. Even if it doesn't crash, this
  331. can still consume a lot of resources, so it is very
  332. important that you are aware of the common pitfalls.
  333. * Events.
  334. Running :mod:`~celery.bin.worker` with the :option:`-E`/:option:`--events`
  335. option will send messages for events happening inside of the worker.
  336. Events should only be enabled if you have an active monitor consuming them,
  337. or if you purge the event queue periodically.
  338. * AMQP backend results.
  339. When running with the AMQP result backend, every task result will be sent
  340. as a message. If you don't collect these results, they will build up and
  341. RabbitMQ will eventually run out of memory.
  342. Results expire after 1 day by default. It may be a good idea
  343. to lower this value by configuring the :setting:`CELERY_TASK_RESULT_EXPIRES`
  344. setting.
  345. If you don't use the results for a task, make sure you set the
  346. `ignore_result` option:
  347. .. code-block python
  348. @celery.task(ignore_result=True)
  349. def mytask():
  350. ...
  351. class MyTask(Task):
  352. ignore_result = True
  353. .. _faq-use-celery-with-stomp:
  354. Can I use Celery with ActiveMQ/STOMP?
  355. -------------------------------------
  356. **Answer**: No. It used to be supported by Carrot,
  357. but is not currently supported in Kombu.
  358. .. _faq-non-amqp-missing-features:
  359. What features are not supported when not using an AMQP broker?
  360. --------------------------------------------------------------
  361. This is an incomplete list of features not available when
  362. using the virtual transports:
  363. * Remote control commands (supported only by Redis).
  364. * Monitoring with events may not work in all virtual transports.
  365. * The `header` and `fanout` exchange types
  366. (`fanout` is supported by Redis).
  367. .. _faq-tasks:
  368. Tasks
  369. =====
  370. .. _faq-tasks-connection-reuse:
  371. How can I reuse the same connection when calling tasks?
  372. -------------------------------------------------------
  373. **Answer**: See the :setting:`BROKER_POOL_LIMIT` setting.
  374. The connection pool is enabled by default since version 2.5.
  375. .. _faq-sudo-subprocess:
  376. Sudo in a :mod:`subprocess` returns :const:`None`
  377. -------------------------------------------------
  378. There is a sudo configuration option that makes it illegal for process
  379. without a tty to run sudo::
  380. Defaults requiretty
  381. If you have this configuration in your :file:`/etc/sudoers` file then
  382. tasks will not be able to call sudo when the worker is running as a daemon.
  383. If you want to enable that, then you need to remove the line from sudoers.
  384. See: http://timelordz.com/wiki/Apache_Sudo_Commands
  385. .. _faq-deletes-unknown-tasks:
  386. Why do workers delete tasks from the queue if they are unable to process them?
  387. ------------------------------------------------------------------------------
  388. **Answer**:
  389. The worker rejects unknown tasks, messages with encoding errors and messages
  390. that doesn't contain the proper fields (as per the task message protocol).
  391. If it did not reject them they could be redelivered again and again,
  392. causing a loop.
  393. Recent versions of RabbitMQ has the ability to configure a dead-letter
  394. queue for exchange, so that rejected messages is moved there.
  395. .. _faq-execute-task-by-name:
  396. Can I call a task by name?
  397. -----------------------------
  398. **Answer**: Yes. Use :func:`celery.execute.send_task`.
  399. You can also call a task by name from any language
  400. that has an AMQP client.
  401. >>> from celery.execute import send_task
  402. >>> send_task("tasks.add", args=[2, 2], kwargs={})
  403. <AsyncResult: 373550e8-b9a0-4666-bc61-ace01fa4f91d>
  404. .. _faq-get-current-task-id:
  405. How can I get the task id of the current task?
  406. ----------------------------------------------
  407. **Answer**: The current id and more is available in the task request::
  408. @celery.task(bind=True)
  409. def mytask(self):
  410. cache.set(self.request.id, "Running")
  411. For more information see :ref:`task-request-info`.
  412. .. _faq-custom-task-ids:
  413. Can I specify a custom task_id?
  414. -------------------------------
  415. **Answer**: Yes. Use the `task_id` argument to :meth:`Task.apply_async`::
  416. >>> task.apply_async(args, kwargs, task_id="...")
  417. Can I use decorators with tasks?
  418. --------------------------------
  419. **Answer**: Yes. But please see note in the sidebar at :ref:`task-basics`.
  420. .. _faq-natural-task-ids:
  421. Can I use natural task ids?
  422. ---------------------------
  423. **Answer**: Yes, but make sure it is unique, as the behavior
  424. for two tasks existing with the same id is undefined.
  425. The world will probably not explode, but at the worst
  426. they can overwrite each others results.
  427. .. _faq-task-callbacks:
  428. How can I run a task once another task has finished?
  429. ----------------------------------------------------
  430. **Answer**: You can safely launch a task inside a task.
  431. Also, a common pattern is to add callbacks to tasks:
  432. .. code-block:: python
  433. from celery.utils.log import get_task_logger
  434. logger = get_task_logger(__name__)
  435. @celery.task
  436. def add(x, y):
  437. return x + y
  438. @celery.task(ignore_result=True)
  439. def log_result(result):
  440. logger.info("log_result got: %r", result)
  441. Invocation::
  442. >>> (add.s(2, 2) | log_result.s()).delay()
  443. See :doc:`userguide/canvas` for more information.
  444. .. _faq-cancel-task:
  445. Can I cancel the execution of a task?
  446. -------------------------------------
  447. **Answer**: Yes. Use `result.revoke`::
  448. >>> result = add.apply_async(args=[2, 2], countdown=120)
  449. >>> result.revoke()
  450. or if you only have the task id::
  451. >>> from celery import current_app as celery
  452. >>> celery.control.revoke(task_id)
  453. .. _faq-node-not-receiving-broadcast-commands:
  454. Why aren't my remote control commands received by all workers?
  455. --------------------------------------------------------------
  456. **Answer**: To receive broadcast remote control commands, every worker node
  457. uses its host name to create a unique queue name to listen to,
  458. so if you have more than one worker with the same host name, the
  459. control commands will be received in round-robin between them.
  460. To work around this you can explicitly set the nodename for every worker
  461. using the :option:`-n` argument to :mod:`~celery.bin.worker`:
  462. .. code-block:: bash
  463. $ celery worker -n worker1@%h
  464. $ celery worker -n worker2@%h
  465. where ``%h`` is automatically expanded into the current hostname.
  466. .. _faq-task-routing:
  467. Can I send some tasks to only some servers?
  468. --------------------------------------------
  469. **Answer:** Yes. You can route tasks to an arbitrary server using AMQP,
  470. and a worker can bind to as many queues as it wants.
  471. See :doc:`userguide/routing` for more information.
  472. .. _faq-change-periodic-task-interval-at-runtime:
  473. Can I change the interval of a periodic task at runtime?
  474. --------------------------------------------------------
  475. **Answer**: Yes. You can use the Django database scheduler, or you can
  476. override `PeriodicTask.is_due` or turn `PeriodicTask.run_every` into a
  477. property:
  478. .. code-block:: python
  479. class MyPeriodic(PeriodicTask):
  480. def run(self):
  481. # ...
  482. @property
  483. def run_every(self):
  484. return get_interval_from_database(...)
  485. .. _faq-task-priorities:
  486. Does celery support task priorities?
  487. ------------------------------------
  488. **Answer**: No. In theory, yes, as AMQP supports priorities. However
  489. RabbitMQ doesn't implement them yet.
  490. The usual way to prioritize work in Celery, is to route high priority tasks
  491. to different servers. In the real world this may actually work better than per message
  492. priorities. You can use this in combination with rate limiting to achieve a
  493. highly responsive system.
  494. .. _faq-acks_late-vs-retry:
  495. Should I use retry or acks_late?
  496. --------------------------------
  497. **Answer**: Depends. It's not necessarily one or the other, you may want
  498. to use both.
  499. `Task.retry` is used to retry tasks, notably for expected errors that
  500. is catchable with the `try:` block. The AMQP transaction is not used
  501. for these errors: **if the task raises an exception it is still acknowledged!**.
  502. The `acks_late` setting would be used when you need the task to be
  503. executed again if the worker (for some reason) crashes mid-execution.
  504. It's important to note that the worker is not known to crash, and if
  505. it does it is usually an unrecoverable error that requires human
  506. intervention (bug in the worker, or task code).
  507. In an ideal world you could safely retry any task that has failed, but
  508. this is rarely the case. Imagine the following task:
  509. .. code-block:: python
  510. @celery.task
  511. def process_upload(filename, tmpfile):
  512. # Increment a file count stored in a database
  513. increment_file_counter()
  514. add_file_metadata_to_db(filename, tmpfile)
  515. copy_file_to_destination(filename, tmpfile)
  516. If this crashed in the middle of copying the file to its destination
  517. the world would contain incomplete state. This is not a critical
  518. scenario of course, but you can probably imagine something far more
  519. sinister. So for ease of programming we have less reliability;
  520. It's a good default, users who require it and know what they
  521. are doing can still enable acks_late (and in the future hopefully
  522. use manual acknowledgement)
  523. In addition `Task.retry` has features not available in AMQP
  524. transactions: delay between retries, max retries, etc.
  525. So use retry for Python errors, and if your task is idempotent
  526. combine that with `acks_late` if that level of reliability
  527. is required.
  528. .. _faq-schedule-at-specific-time:
  529. Can I schedule tasks to execute at a specific time?
  530. ---------------------------------------------------
  531. .. module:: celery.task.base
  532. **Answer**: Yes. You can use the `eta` argument of :meth:`Task.apply_async`.
  533. Or to schedule a periodic task at a specific time, use the
  534. :class:`celery.schedules.crontab` schedule behavior:
  535. .. code-block:: python
  536. from celery.schedules import crontab
  537. from celery.task import periodic_task
  538. @periodic_task(run_every=crontab(hour=7, minute=30, day_of_week="mon"))
  539. def every_monday_morning():
  540. print("This is run every Monday morning at 7:30")
  541. .. _faq-safe-worker-shutdown:
  542. How can I safely shut down the worker?
  543. --------------------------------------
  544. **Answer**: Use the :sig:`TERM` signal, and the worker will finish all currently
  545. executing jobs and shut down as soon as possible. No tasks should be lost.
  546. You should never stop :mod:`~celery.bin.worker` with the :sig:`KILL` signal
  547. (:option:`-9`), unless you've tried :sig:`TERM` a few times and waited a few
  548. minutes to let it get a chance to shut down. As if you do tasks may be
  549. terminated mid-execution, and they will not be re-run unless you have the
  550. `acks_late` option set (`Task.acks_late` / :setting:`CELERY_ACKS_LATE`).
  551. .. seealso::
  552. :ref:`worker-stopping`
  553. .. _faq-daemonizing:
  554. How do I run the worker in the background on [platform]?
  555. --------------------------------------------------------
  556. **Answer**: Please see :ref:`daemonizing`.
  557. .. _faq-django:
  558. Django
  559. ======
  560. .. _faq-django-database-tables:
  561. What purpose does the database tables created by django-celery have?
  562. --------------------------------------------------------------------
  563. Several database tables are created by default, these relate to
  564. * Monitoring
  565. When you use the django-admin monitor, the cluster state is written
  566. to the ``TaskState`` and ``WorkerState`` models.
  567. * Periodic tasks
  568. When the database-backed schedule is used the periodic task
  569. schedule is taken from the ``PeriodicTask`` model, there are
  570. also several other helper tables (``IntervalSchedule``,
  571. ``CrontabSchedule``, ``PeriodicTasks``).
  572. * Task results
  573. The database result backend is enabled by default when using django-celery
  574. (this is for historical reasons, and thus for backward compatibility).
  575. The results are stored in the ``TaskMeta`` and ``TaskSetMeta`` models.
  576. *these tables are not created if another result backend is configured*.
  577. .. _faq-windows:
  578. Windows
  579. =======
  580. .. _faq-windows-worker-embedded-beat:
  581. The `-B` / `--beat` option to worker doesn't work?
  582. ----------------------------------------------------------------
  583. **Answer**: That's right. Run `celery beat` and `celery worker` as separate
  584. services instead.