faq.rst 29 KB

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