FAQ 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876
  1. ============================
  2. Frequently Asked Questions
  3. ============================
  4. General
  5. =======
  6. What kinds of things should I use celery for?
  7. ---------------------------------------------
  8. **Answer:** `Queue everything and delight everyone`_ is a good article
  9. describing why you would use a queue in a web context.
  10. .. _`Queue everything and delight everyone`:
  11. http://decafbad.com/blog/2008/07/04/queue-everything-and-delight-everyone
  12. These are some common use cases:
  13. * Running something in the background. For example, to finish the web request
  14. as soon as possible, then update the users page incrementally.
  15. This gives the user the impression of good performane and "snappiness", even
  16. though the real work might actually take some time.
  17. * Running something after the web request has finished.
  18. * Making sure something is done, by executing it asynchronously and using
  19. retries.
  20. * Scheduling periodic work.
  21. And to some degree:
  22. * Distributed computing.
  23. * Parallel execution.
  24. Misconceptions
  25. ==============
  26. Is celery dependent on pickle?
  27. ------------------------------
  28. **Answer:** No.
  29. Celery can support any serialization scheme and has support for JSON/YAML and
  30. Pickle by default. You can even send one task using pickle, and another one
  31. with JSON seamlessly, this is because every task is associated with a
  32. content-type. The default serialization scheme is pickle because it's the most
  33. used, and it has support for sending complex objects as task arguments.
  34. You can set a global default serializer, the default serializer for a
  35. particular Task, or even what serializer to use when sending a single task
  36. instance.
  37. Is celery for Django only?
  38. --------------------------
  39. **Answer:** No.
  40. You can use all of the features without using Django.
  41. Why is Django a dependency?
  42. ---------------------------
  43. Celery uses the Django ORM for database access when using the database result
  44. backend, the Django cache framework when using the cache result backend, and the Django signal
  45. dispatch mechanisms for signaling.
  46. This doesn't mean you need to have a Django project to use celery, it
  47. just means that sometimes we use internal Django components.
  48. The long term plan is to replace these with other solutions, (e.g. `SQLAlchemy`_ as the ORM,
  49. and `louie`_, for signaling). The celery distribution will be split into two:
  50. * celery
  51. The core. Using SQLAlchemy for the database backend.
  52. * django-celery
  53. Celery integration for Django, using the Django ORM for the database
  54. backend.
  55. We're currently seeking people with `SQLAlchemy`_ experience, so please
  56. contact the project if you want this done sooner.
  57. The reason for the split is for purity only. It shouldn't affect you much as a
  58. user, so please don't worry about the Django dependency, just have a good time
  59. using celery.
  60. .. _`SQLAlchemy`: http://www.sqlalchemy.org/
  61. .. _`louie`: http://pypi.python.org/pypi/Louie/
  62. Do I have to use AMQP/RabbitMQ?
  63. -------------------------------
  64. **Answer**: No.
  65. You can also use Redis or an SQL database, see `Using other
  66. queues`_.
  67. .. _`Using other queues`:
  68. http://ask.github.com/celery/tutorials/otherqueues.html
  69. Redis or a database won't perform as well as
  70. an AMQP broker. If you have strict reliability requirements you are
  71. encouraged to use RabbitMQ or another AMQP broker. Redis/database also use
  72. polling, so they are likely to consume more resources. However, if you for
  73. some reason are not able to use AMQP, feel free to use these alternatives.
  74. They will probably work fine for most use cases, and note that the above
  75. points are not specific to celery; If using Redis/database as a queue worked
  76. fine for you before, it probably will now. You can always upgrade later
  77. if you need to.
  78. Is celery multi-lingual?
  79. ------------------------
  80. **Answer:** Yes.
  81. celeryd is an implementation of celery in python. If the language has an AMQP
  82. client, there shouldn't be much work to create a worker in your language.
  83. A celery worker is just a program connecting to the broker to consume
  84. messages. There's no other communication involved.
  85. Also, there's another way to be language indepedent, and that is to use REST
  86. tasks, instead of your tasks being functions, they're URLs. With this
  87. information you can even create simple web servers that enable preloading of
  88. code. See: `User Guide: Remote Tasks`_.
  89. .. _`User Guide: Remote Tasks`:
  90. http://ask.github.com/celery/userguide/remote-tasks.html
  91. Troubleshooting
  92. ===============
  93. MySQL is throwing deadlock errors, what can I do?
  94. -------------------------------------------------
  95. **Answer:** MySQL has default isolation level set to ``REPEATABLE-READ``,
  96. if you don't really need that, set it to ``READ-COMMITTED``.
  97. You can do that by adding the following to your ``my.cnf``::
  98. [mysqld]
  99. transaction-isolation = READ-COMMITTED
  100. For more information about InnoDBs transaction model see `MySQL - The InnoDB
  101. Transaction Model and Locking`_ in the MySQL user manual.
  102. (Thanks to Honza Kral and Anton Tsigularov for this solution)
  103. .. _`MySQL - The InnoDB Transaction Model and Locking`: http://dev.mysql.com/doc/refman/5.1/en/innodb-transaction-model.html
  104. celeryd is not doing anything, just hanging
  105. --------------------------------------------
  106. **Answer:** See `MySQL is throwing deadlock errors, what can I do?`_.
  107. or `Why is Task.delay/apply\* just hanging?`.
  108. Why is Task.delay/apply\*/celeryd just hanging?
  109. -----------------------------------------------
  110. **Answer:** There is a bug in some AMQP clients that will make it hang if
  111. it's not able to authenticate the current user, the password doesn't match or
  112. the user does not have access to the virtual host specified. Be sure to check
  113. your broker logs (for RabbitMQ that is ``/var/log/rabbitmq/rabbit.log`` on
  114. most systems), it usually contains a message describing the reason.
  115. Why won't celeryd run on FreeBSD?
  116. ---------------------------------
  117. **Answer:** multiprocessing.Pool requires a working POSIX semaphore
  118. implementation which isn't enabled in FreeBSD by default. You have to enable
  119. POSIX semaphores in the kernel and manually recompile multiprocessing.
  120. Luckily, Viktor Petersson has written a tutorial to get you started with
  121. Celery on FreeBSD here:
  122. http://www.playingwithwire.com/2009/10/how-to-get-celeryd-to-work-on-freebsd/
  123. I'm having ``IntegrityError: Duplicate Key`` errors. Why?
  124. ---------------------------------------------------------
  125. **Answer:** See `MySQL is throwing deadlock errors, what can I do?`_.
  126. Thanks to howsthedotcom.
  127. Why aren't my tasks processed?
  128. ------------------------------
  129. **Answer:** With RabbitMQ you can see how many consumers are currently
  130. receiving tasks by running the following command::
  131. $ rabbitmqctl list_queues -p <myvhost> name messages consumers
  132. Listing queues ...
  133. celery 2891 2
  134. This shows that there's 2891 messages waiting to be processed in the task
  135. queue, and there are two consumers processing them.
  136. One reason that the queue is never emptied could be that you have a stale
  137. celery process taking the messages hostage. This could happen if celeryd
  138. wasn't properly shut down.
  139. When a message is recieved by a worker the broker waits for it to be
  140. acknowledged before marking the message as processed. The broker will not
  141. re-send that message to another consumer until the consumer is shut down
  142. properly.
  143. If you hit this problem you have to kill all workers manually and restart
  144. them::
  145. ps auxww | grep celeryd | awk '{print $2}' | xargs kill
  146. You might have to wait a while until all workers have finished the work they're
  147. doing. If it's still hanging after a long time you can kill them by force
  148. with::
  149. ps auxww | grep celeryd | awk '{print $2}' | xargs kill -9
  150. Why won't my Task run?
  151. ----------------------
  152. **Answer:** Did you register the task in the applications ``tasks.py`` module?
  153. (or in some other module Django loads by default, like ``models.py``?).
  154. Also there might be syntax errors preventing the tasks module being imported.
  155. You can find out if celery is able to run the task by executing the
  156. task manually:
  157. >>> from myapp.tasks import MyPeriodicTask
  158. >>> MyPeriodicTask.delay()
  159. Watch celeryds logfile to see if it's able to find the task, or if some
  160. other error is happening.
  161. Why won't my Periodic Task run?
  162. -------------------------------
  163. **Answer:** See `Why won't my Task run?`_.
  164. How do I discard all waiting tasks?
  165. ------------------------------------
  166. **Answer:** Use ``celery.task.discard_all()``, like this:
  167. >>> from celery.task import discard_all
  168. >>> discard_all()
  169. 1753
  170. The number ``1753`` is the number of messages deleted.
  171. You can also start celeryd with the ``--discard`` argument which will
  172. accomplish the same thing.
  173. I've discarded messages, but there are still messages left in the queue?
  174. ------------------------------------------------------------------------
  175. **Answer:** Tasks are acknowledged (removed from the queue) as soon
  176. as they are actually executed. After the worker has received a task, it will
  177. take some time until it is actually executed, especially if there are a lot
  178. of tasks already waiting for execution. Messages that are not acknowledged are
  179. hold on to by the worker until it closes the connection to the broker (AMQP
  180. server). When that connection is closed (e.g because the worker was stopped)
  181. the tasks will be re-sent by the broker to the next available worker (or the
  182. same worker when it has been restarted), so to properly purge the queue of
  183. waiting tasks you have to stop all the workers, and then discard the tasks
  184. using ``discard_all``.
  185. Windows: The ``-B`` / ``--beat`` option to celeryd doesn't work?
  186. ----------------------------------------------------------------
  187. **Answer**: That's right. Run ``celerybeat`` and ``celeryd`` as separate
  188. services instead.
  189. Tasks
  190. =====
  191. How can I reuse the same connection when applying tasks?
  192. --------------------------------------------------------
  193. **Answer**: See :doc:`userguide/executing`.
  194. Can I execute a task by name?
  195. -----------------------------
  196. **Answer**: Yes. Use :func:`celery.execute.send_task`.
  197. You can also execute a task by name from any language
  198. that has an AMQP client.
  199. >>> from celery.execute import send_task
  200. >>> send_task("tasks.add", args=[2, 2], kwargs={})
  201. <AsyncResult: 373550e8-b9a0-4666-bc61-ace01fa4f91d>
  202. Results
  203. =======
  204. How dow I get the result of a task if I have the ID that points there?
  205. ----------------------------------------------------------------------
  206. **Answer**: Use ``Task.AsyncResult``::
  207. >>> result = MyTask.AsyncResult(task_id)
  208. >>> result.get()
  209. This will give you a :class:`celery.result.BaseAsyncResult` instance
  210. using the tasks current result backend.
  211. If you need to specify a custom result backend you should use
  212. :class:`celery.result.BaseAsyncResult` directly::
  213. >>> from celery.result import BaseAsyncResult
  214. >>> result = BaseAsyncResult(task_id, backend=...)
  215. >>> result.get()
  216. Brokers
  217. =======
  218. Why is RabbitMQ crashing?
  219. -------------------------
  220. RabbitMQ will crash if it runs out of memory. This will be fixed in a
  221. future release of RabbitMQ. please refer to the RabbitMQ FAQ:
  222. http://www.rabbitmq.com/faq.html#node-runs-out-of-memory
  223. Some common Celery misconfigurations can crash RabbitMQ:
  224. * Events.
  225. Running ``celeryd`` with the ``-E``/``--events`` option will send messages
  226. for events happening inside of the worker. If these event messages
  227. are not consumed, you will eventually run out of memory.
  228. Events should only be enabled if you have an active monitor consuming them.
  229. * AMQP backend results.
  230. When running with the AMQP result backend, every task result will be sent
  231. as a message. If you don't collect these results, they will build up and
  232. RabbitMQ will eventually run out of memory.
  233. If you don't use the results for a task, make sure you set the
  234. ``ignore_result`` option:
  235. .. code-block python
  236. @task(ignore_result=True)
  237. def mytask():
  238. ...
  239. class MyTask(Task):
  240. ignore_result = True
  241. Results can also be disabled globally using the ``CELERY_IGNORE_RESULT``
  242. setting.
  243. Can I use celery with ActiveMQ/STOMP?
  244. -------------------------------------
  245. **Answer**: Yes, but this is somewhat experimental for now.
  246. It is working ok in a test configuration, but it has not
  247. been tested in production like RabbitMQ has. If you have any problems with
  248. using STOMP and celery, please report the bugs to the issue tracker:
  249. http://github.com/ask/celery/issues/
  250. First you have to use the ``master`` branch of ``celery``::
  251. $ git clone git://github.com/ask/celery.git
  252. $ cd celery
  253. $ sudo python setup.py install
  254. $ cd ..
  255. Then you need to install the ``stompbackend`` branch of ``carrot``::
  256. $ git clone git://github.com/ask/carrot.git
  257. $ cd carrot
  258. $ git checkout stompbackend
  259. $ sudo python setup.py install
  260. $ cd ..
  261. And my fork of ``python-stomp`` which adds non-blocking support::
  262. $ hg clone http://bitbucket.org/asksol/python-stomp/
  263. $ cd python-stomp
  264. $ sudo python setup.py install
  265. $ cd ..
  266. In this example we will use a queue called ``celery`` which we created in
  267. the ActiveMQ web admin interface.
  268. **Note**: For ActiveMQ the queue name has to have ``"/queue/"`` prepended to
  269. it. i.e. the queue ``celery`` becomes ``/queue/celery``.
  270. Since a STOMP queue is a single named entity and it doesn't have the
  271. routing capabilities of AMQP you need to set both the ``queue``, and
  272. ``exchange`` settings to your queue name. This is a minor inconvenience since
  273. carrot needs to maintain the same interface for both AMQP and STOMP (obviously
  274. the one with the most capabilities won).
  275. Use the following specific settings in your ``settings.py``:
  276. .. code-block:: python
  277. # Makes python-stomp the default backend for carrot.
  278. CARROT_BACKEND = "stomp"
  279. # STOMP hostname and port settings.
  280. BROKER_HOST = "localhost"
  281. BROKER_PORT = 61613
  282. # The queue name to use (both queue and exchange must be set to the
  283. # same queue name when using STOMP)
  284. CELERY_DEFAULT_QUEUE = "/queue/celery"
  285. CELERY_DEFAULT_EXCHANGE = "/queue/celery"
  286. CELERY_QUEUES = {
  287. "/queue/celery": {"exchange": "/queue/celery"}
  288. }
  289. Now you can go on reading the tutorial in the README, ignoring any AMQP
  290. specific options.
  291. What features are not supported when using STOMP?
  292. --------------------------------------------------
  293. This is a (possible incomplete) list of features not available when
  294. using the STOMP backend:
  295. * routing keys
  296. * exchange types (direct, topic, headers, etc)
  297. * immediate
  298. * mandatory
  299. Features
  300. ========
  301. How can I run a task once another task has finished?
  302. ----------------------------------------------------
  303. **Answer**: You can safely launch a task inside a task.
  304. Also, a common pattern is to use callback tasks:
  305. .. code-block:: python
  306. @task()
  307. def add(x, y, callback=None):
  308. result = x + y
  309. if callback:
  310. callback.delay(result)
  311. return result
  312. @task(ignore_result=True)
  313. def log_result(result, **kwargs):
  314. logger = log_result.get_logger(**kwargs)
  315. logger.info("log_result got: %s" % (result, ))
  316. >>> add.delay(2, 2, callback=log_result)
  317. Can I cancel the execution of a task?
  318. -------------------------------------
  319. **Answer**: Yes. Use ``result.revoke``::
  320. >>> result = add.apply_async(args=[2, 2], countdown=120)
  321. >>> result.revoke()
  322. or if you only have the task id::
  323. >>> from celery.task.control import revoke
  324. >>> revoke(task_id)
  325. Why aren't my remote control commands received by all workers?
  326. --------------------------------------------------------------
  327. **Answer**: To receive broadcast remote control commands, every ``celeryd``
  328. uses its hostname to create a unique queue name to listen to,
  329. so if you have more than one worker with the same hostname, the
  330. control commands will be recieved in round-robin between them.
  331. To work around this you can explicitly set the hostname for every worker
  332. using the ``--hostname`` argument to ``celeryd``::
  333. $ celeryd --hostname=$(hostname).1
  334. $ celeryd --hostname=$(hostname).2
  335. etc, etc.
  336. Can I send some tasks to only some servers?
  337. --------------------------------------------
  338. **Answer:** Yes. You can route tasks to an arbitrary server using AMQP,
  339. and a worker can bind to as many queues as it wants.
  340. Say you have two servers, ``x``, and ``y`` that handles regular tasks,
  341. and one server ``z``, that only handles feed related tasks, you can use this
  342. configuration:
  343. * Servers ``x`` and ``y``: settings.py:
  344. .. code-block:: python
  345. CELERY_DEFAULT_QUEUE = "regular_tasks"
  346. CELERY_QUEUES = {
  347. "regular_tasks": {
  348. "binding_key": "task.#",
  349. },
  350. }
  351. CELERY_DEFAULT_EXCHANGE = "tasks"
  352. CELERY_DEFAULT_EXCHANGE_TYPE = "topic"
  353. CELERY_DEFAULT_ROUTING_KEY = "task.regular"
  354. * Server ``z``: settings.py:
  355. .. code-block:: python
  356. CELERY_DEFAULT_QUEUE = "feed_tasks"
  357. CELERY_QUEUES = {
  358. "feed_tasks": {
  359. "binding_key": "feed.#",
  360. },
  361. }
  362. CELERY_DEFAULT_EXCHANGE = "tasks"
  363. CELERY_DEFAULT_ROUTING_KEY = "task.regular"
  364. CELERY_DEFAULT_EXCHANGE_TYPE = "topic"
  365. ``CELERY_QUEUES`` is a map of queue names and their exchange/type/binding_key,
  366. if you don't set exchange or exchange type, they will be taken from the
  367. ``CELERY_DEFAULT_EXCHANGE``/``CELERY_DEFAULT_EXCHANGE_TYPE`` settings.
  368. Now to make a Task run on the ``z`` server you need to set its
  369. ``routing_key`` attribute so it starts with the words ``"task.feed."``:
  370. .. code-block:: python
  371. from feedaggregator.models import Feed
  372. from celery.decorators import task
  373. @task(routing_key="feed.importer")
  374. def import_feed(feed_url):
  375. Feed.objects.import_feed(feed_url)
  376. or if subclassing the ``Task`` class directly:
  377. .. code-block:: python
  378. class FeedImportTask(Task):
  379. routing_key = "feed.importer"
  380. def run(self, feed_url):
  381. Feed.objects.import_feed(feed_url)
  382. You can also override this using the ``routing_key`` argument to
  383. :func:`celery.task.apply_async`:
  384. >>> from myapp.tasks import RefreshFeedTask
  385. >>> RefreshFeedTask.apply_async(args=["http://cnn.com/rss"],
  386. ... routing_key="feed.importer")
  387. If you want, you can even have your feed processing worker handle regular
  388. tasks as well, maybe in times when there's a lot of work to do.
  389. Just add a new queue to server ``z``'s ``CELERY_QUEUES``:
  390. .. code-block:: python
  391. CELERY_QUEUES = {
  392. "feed_tasks": {
  393. "binding_key": "feed.#",
  394. },
  395. "regular_tasks": {
  396. "binding_key": "task.#",
  397. },
  398. }
  399. Since the default exchange is ``tasks``, they will both use the same
  400. exchange.
  401. If you have another queue but on another exchange you want to add,
  402. just specify a custom exchange and exchange type:
  403. .. code-block:: python
  404. CELERY_QUEUES = {
  405. "feed_tasks": {
  406. "binding_key": "feed.#",
  407. },
  408. "regular_tasks": {
  409. "binding_key": "task.#",
  410. }
  411. "image_tasks": {
  412. "binding_key": "image.compress",
  413. "exchange": "mediatasks",
  414. "exchange_type": "direct",
  415. },
  416. }
  417. If you're confused about these terms, you should read up on AMQP and RabbitMQ.
  418. `Rabbits and Warrens`_ is an excellent blog post describing queues and
  419. exchanges. There's also AMQP in 10 minutes*: `Flexible Routing Model`_,
  420. and `Standard Exchange Types`_. For users of RabbitMQ the `RabbitMQ FAQ`_
  421. could also be useful as a source of information.
  422. .. _`Rabbits and Warrens`: http://blogs.digitar.com/jjww/2009/01/rabbits-and-warrens/
  423. .. _`Flexible Routing Model`: http://bit.ly/95XFO1
  424. .. _`Standard Exchange Types`: http://bit.ly/EEWca
  425. .. _`RabbitMQ FAQ`: http://www.rabbitmq.com/faq.html
  426. Can I use celery without Django?
  427. --------------------------------
  428. **Answer:** Yes.
  429. Celery uses something called loaders to read/setup configuration, import
  430. modules that register tasks and to decide what happens when a task is
  431. executed. Currently there are two loaders, the default loader and the Django
  432. loader. If you want to use celery without a Django project, you either have to
  433. use the default loader, or write a loader of your own.
  434. The rest of this answer describes how to use the default loader.
  435. While it is possible to use Celery from outside of Django, we still need
  436. Django itself to run, this is to use the ORM and cache-framework.
  437. Duplicating these features would be time consuming and mostly pointless, so
  438. while me might rewrite these in the future, this is a good solution in the
  439. mean time.
  440. Install Django using your favorite install tool, ``easy_install``, ``pip``, or
  441. whatever::
  442. # easy_install django # as root
  443. You need a configuration file named ``celeryconfig.py``, either in the
  444. directory you run ``celeryd`` in, or in a Python library path where it is
  445. able to find it. The configuration file can contain any of the settings
  446. described in :mod:`celery.conf`. In addition; if you're using the
  447. database backend you have to configure the database. Here is an example
  448. configuration using the database backend with MySQL:
  449. .. code-block:: python
  450. # Broker configuration
  451. BROKER_HOST = "localhost"
  452. BROKER_PORT = "5672"
  453. BROKER_VHOST = "celery"
  454. BROKER_USER = "celery"
  455. BROKER_PASSWORD = "celerysecret"
  456. CARROT_BACKEND="amqp"
  457. # Using the database backend.
  458. CELERY_RESULT_BACKEND = "database"
  459. DATABASE_ENGINE = "mysql" # see Django docs for a description of these.
  460. DATABASE_NAME = "mydb"
  461. DATABASE_HOST = "mydb.example.org"
  462. DATABASE_USER = "myuser"
  463. DATABASE_PASSWORD = "mysecret"
  464. # Number of processes that processes tasks simultaneously.
  465. CELERYD_CONCURRENCY = 8
  466. # Modules to import when celeryd starts.
  467. # This must import every module where you register tasks so celeryd
  468. # is able to find and run them.
  469. CELERY_IMPORTS = ("mytaskmodule1", "mytaskmodule2")
  470. With this configuration file in the current directory you have to
  471. run ``celeryinit`` to create the database tables::
  472. $ celeryinit
  473. At this point you should be able to successfully run ``celeryd``::
  474. $ celeryd --loglevel=INFO
  475. and send a task from a python shell (note that it must be able to import
  476. ``celeryconfig.py``):
  477. >>> from celery.task.builtins import PingTask
  478. >>> result = PingTask.apply_async()
  479. >>> result.get()
  480. 'pong'
  481. The celery test-suite is failing
  482. --------------------------------
  483. **Answer**: If you're running tests from your Django project, and the celery
  484. test suite is failing in that context, then follow the steps below. If the
  485. celery tests are failing in another context, please report an issue to our
  486. issue tracker at GitHub:
  487. http://github.com/ask/celery/issues/
  488. That Django is running tests for all applications in ``INSTALLED_APPS``
  489. by default is a pet peeve for many. You should use a test runner that either
  490. 1) Explicitly lists the apps you want to run tests for, or
  491. 2) Make a test runner that skips tests for apps you don't want to run.
  492. For example the test runner that celery is using:
  493. http://bit.ly/NVKep
  494. To use this test runner, add the following to your ``settings.py``:
  495. .. code-block:: python
  496. TEST_RUNNER = "celery.tests.runners.run_tests"
  497. TEST_APPS = (
  498. "app1",
  499. "app2",
  500. "app3",
  501. "app4",
  502. )
  503. Or, if you just want to skip the celery tests:
  504. .. code-block:: python
  505. INSTALLED_APPS = (.....)
  506. TEST_RUNNER = "celery.tests.runners.run_tests"
  507. TEST_APPS = filter(lambda k: k != "celery", INSTALLED_APPS)
  508. Can I change the interval of a periodic task at runtime?
  509. --------------------------------------------------------
  510. **Answer**: Yes. You can override ``PeriodicTask.is_due`` or turn
  511. ``PeriodicTask.run_every`` into a property:
  512. .. code-block:: python
  513. class MyPeriodic(PeriodicTask):
  514. def run(self):
  515. # ...
  516. @property
  517. def run_every(self):
  518. return get_interval_from_database(...)
  519. Does celery support task priorities?
  520. ------------------------------------
  521. **Answer**: No. In theory, yes, as AMQP supports priorities. However
  522. RabbitMQ doesn't implement them yet.
  523. The usual way to prioritize work in celery, is to route high priority tasks
  524. to different servers. In the real world this may actually work better than per message
  525. priorities. You can use this in combination with rate limiting to achieve a
  526. highly performant system.
  527. Should I use retry or acks_late?
  528. --------------------------------
  529. **Answer**: Depends. It's not necessarily one or the other, you may want
  530. to use both.
  531. ``Task.retry`` is used to retry tasks, notably for expected errors that
  532. is catchable with the ``try:`` block. The AMQP transaction is not used
  533. for these errors: **if the task raises an exception it is still acked!**.
  534. The ``acks_late`` setting would be used when you need the task to be
  535. executed again if the worker (for some reason) crashes mid-execution.
  536. It's important to note that the worker is not known to crash, and if
  537. it does it is usually an unrecoverable error that requires human
  538. intervention (bug in the worker, or task code).
  539. In an ideal world you could safely retry any task that has failed, but
  540. this is rarely the case. Imagine the following task:
  541. .. code-block:: python
  542. @task()
  543. def process_upload(filename, tmpfile):
  544. # Increment a file count stored in a database
  545. increment_file_counter()
  546. add_file_metadata_to_db(filename, tmpfile)
  547. copy_file_to_destination(filename, tmpfile)
  548. If this crashed in the middle of copying the file to its destination
  549. the world would contain incomplete state. This is not a critical
  550. scenario of course, but you can probably imagine something far more
  551. sinister. So for ease of programming we have less reliability;
  552. It's a good default, users who require it and know what they
  553. are doing can still enable acks_late (and in the future hopefully
  554. use manual acknowledgement)
  555. In addition ``Task.retry`` has features not available in AMQP
  556. transactions: delay between retries, max retries, etc.
  557. So use retry for Python errors, and if your task is reentrant
  558. combine that with ``acks_late`` if that level of reliability
  559. is required.
  560. Can I schedule tasks to execute at a specific time?
  561. ---------------------------------------------------
  562. .. module:: celery.task.base
  563. **Answer**: Yes. You can use the ``eta`` argument of :meth:`Task.apply_async`.
  564. Or to schedule a periodic task at a specific time, use the
  565. :class:`celery.task.schedules.crontab` schedule behavior:
  566. .. code-block:: python
  567. from celery.task.schedules import crontab
  568. from celery.decorators import periodic_task
  569. @periodic_task(run_every=crontab(hours=7, minute=30, day_of_week="mon"))
  570. def every_monday_morning():
  571. print("This is run every monday morning at 7:30")
  572. How do I shut down ``celeryd`` safely?
  573. --------------------------------------
  574. **Answer**: Use the ``TERM`` signal, and celery will finish all currently
  575. executing jobs and shut down as soon as possible. No tasks should be lost.
  576. You should never stop ``celeryd`` with the ``KILL`` signal (``-9``),
  577. unless you've tried ``TERM`` a few times and waited a few minutes to let it
  578. get a chance to shut down. As if you do tasks may be terminated mid-execution,
  579. and they will not be re-run unless you have the ``acks_late`` option set.
  580. (``Task.acks_late`` / ``CELERY_ACKS_LATE``).
  581. How do I run celeryd in the background on [platform]?
  582. -----------------------------------------------------
  583. **Answer**: Please see :doc:`cookbook/daemonizing`.
  584. Django
  585. ======
  586. Generating a template in a task doesn't seem to respect my i18n settings?
  587. -------------------------------------------------------------------------
  588. **Answer**: To enable the Django translation machinery you need to activate
  589. it with a language. **Note**: Be sure to reset to the previous language when
  590. done.
  591. >>> from django.utils import translation
  592. >>> prev_language = translation.get_language()
  593. >>> translation.activate(language)
  594. >>> try:
  595. ... render_template()
  596. ... finally:
  597. translation.activate(prev_language)
  598. The common pattern here would be for the task to take a ``language``
  599. argument:
  600. .. code-block:: python
  601. from celery.decorators import task
  602. from django.utils import translation
  603. from django.template.loader import render_to_string
  604. @task()
  605. def generate_report(template="report.html", language=None):
  606. prev_language = translation.get_language()
  607. language and translation.activate(language)
  608. try:
  609. report = render_to_string(template)
  610. finally:
  611. translation.activate(prev_language)
  612. save_report_somewhere(report)