faq.rst 28 KB

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