FAQ 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821
  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. Results
  195. =======
  196. How dow I get the result of a task if I have the ID that points there?
  197. ----------------------------------------------------------------------
  198. **Answer**: Use ``Task.AsyncResult``::
  199. >>> result = MyTask.AsyncResult(task_id)
  200. >>> result.get()
  201. This will give you a :class:`celery.result.BaseAsyncResult` instance
  202. using the tasks current result backend.
  203. If you need to specify a custom result backend you should use
  204. :class:`celery.result.BaseAsyncResult` directly::
  205. >>> from celery.result import BaseAsyncResult
  206. >>> result = BaseAsyncResult(task_id, backend=...)
  207. >>> result.get()
  208. Brokers
  209. =======
  210. Why is RabbitMQ crashing?
  211. -------------------------
  212. RabbitMQ will crash if it runs out of memory. This will be fixed in a
  213. future release of RabbitMQ. please refer to the RabbitMQ FAQ:
  214. http://www.rabbitmq.com/faq.html#node-runs-out-of-memory
  215. Some common Celery misconfigurations can crash RabbitMQ:
  216. * Events.
  217. Running ``celeryd`` with the ``-E``/``--events`` option will send messages
  218. for events happening inside of the worker. If these event messages
  219. are not consumed, you will eventually run out of memory.
  220. Events should only be enabled if you have an active monitor consuming them.
  221. * AMQP backend results.
  222. When running with the AMQP result backend, every task result will be sent
  223. as a message. If you don't collect these results, they will build up and
  224. RabbitMQ will eventually run out of memory.
  225. If you don't use the results for a task, make sure you set the
  226. ``ignore_result`` option:
  227. .. code-block python
  228. @task(ignore_result=True)
  229. def mytask():
  230. ...
  231. class MyTask(Task):
  232. ignore_result = True
  233. Results can also be disabled globally using the ``CELERY_IGNORE_RESULT``
  234. setting.
  235. Can I use celery with ActiveMQ/STOMP?
  236. -------------------------------------
  237. **Answer**: Yes, but this is somewhat experimental for now.
  238. It is working ok in a test configuration, but it has not
  239. been tested in production like RabbitMQ has. If you have any problems with
  240. using STOMP and celery, please report the bugs to the issue tracker:
  241. http://github.com/ask/celery/issues/
  242. First you have to use the ``master`` branch of ``celery``::
  243. $ git clone git://github.com/ask/celery.git
  244. $ cd celery
  245. $ sudo python setup.py install
  246. $ cd ..
  247. Then you need to install the ``stompbackend`` branch of ``carrot``::
  248. $ git clone git://github.com/ask/carrot.git
  249. $ cd carrot
  250. $ git checkout stompbackend
  251. $ sudo python setup.py install
  252. $ cd ..
  253. And my fork of ``python-stomp`` which adds non-blocking support::
  254. $ hg clone http://bitbucket.org/asksol/python-stomp/
  255. $ cd python-stomp
  256. $ sudo python setup.py install
  257. $ cd ..
  258. In this example we will use a queue called ``celery`` which we created in
  259. the ActiveMQ web admin interface.
  260. **Note**: For ActiveMQ the queue name has to have ``"/queue/"`` prepended to
  261. it. i.e. the queue ``celery`` becomes ``/queue/celery``.
  262. Since a STOMP queue is a single named entity and it doesn't have the
  263. routing capabilities of AMQP you need to set both the ``queue``, and
  264. ``exchange`` settings to your queue name. This is a minor inconvenience since
  265. carrot needs to maintain the same interface for both AMQP and STOMP (obviously
  266. the one with the most capabilities won).
  267. Use the following specific settings in your ``settings.py``:
  268. .. code-block:: python
  269. # Makes python-stomp the default backend for carrot.
  270. CARROT_BACKEND = "stomp"
  271. # STOMP hostname and port settings.
  272. BROKER_HOST = "localhost"
  273. BROKER_PORT = 61613
  274. # The queue name to use (both queue and exchange must be set to the
  275. # same queue name when using STOMP)
  276. CELERY_DEFAULT_QUEUE = "/queue/celery"
  277. CELERY_DEFAULT_EXCHANGE = "/queue/celery"
  278. CELERY_QUEUES = {
  279. "/queue/celery": {"exchange": "/queue/celery"}
  280. }
  281. Now you can go on reading the tutorial in the README, ignoring any AMQP
  282. specific options.
  283. What features are not supported when using STOMP?
  284. --------------------------------------------------
  285. This is a (possible incomplete) list of features not available when
  286. using the STOMP backend:
  287. * routing keys
  288. * exchange types (direct, topic, headers, etc)
  289. * immediate
  290. * mandatory
  291. Features
  292. ========
  293. How can I run a task once another task has finished?
  294. ----------------------------------------------------
  295. **Answer**: You can safely launch a task inside a task.
  296. Also, a common pattern is to use callback tasks:
  297. .. code-block:: python
  298. @task()
  299. def add(x, y, callback=None):
  300. result = x + y
  301. if callback:
  302. callback.delay(result)
  303. return result
  304. @task(ignore_result=True)
  305. def log_result(result, **kwargs):
  306. logger = log_result.get_logger(**kwargs)
  307. logger.info("log_result got: %s" % (result, ))
  308. >>> add.delay(2, 2, callback=log_result)
  309. Can I cancel the execution of a task?
  310. -------------------------------------
  311. **Answer**: Yes. Use ``result.revoke``::
  312. >>> result = add.apply_async(args=[2, 2], countdown=120)
  313. >>> result.revoke()
  314. or if you only have the task id::
  315. >>> from celery.task.control import revoke
  316. >>> revoke(task_id)
  317. Why aren't my remote control commands received by all workers?
  318. --------------------------------------------------------------
  319. **Answer**: To receive broadcast remote control commands, every ``celeryd``
  320. uses its hostname to create a unique queue name to listen to,
  321. so if you have more than one worker with the same hostname, the
  322. control commands will be recieved in round-robin between them.
  323. To work around this you can explicitly set the hostname for every worker
  324. using the ``--hostname`` argument to ``celeryd``::
  325. $ celeryd --hostname=$(hostname).1
  326. $ celeryd --hostname=$(hostname).2
  327. etc, etc.
  328. Can I send some tasks to only some servers?
  329. --------------------------------------------
  330. **Answer:** Yes. You can route tasks to an arbitrary server using AMQP,
  331. and a worker can bind to as many queues as it wants.
  332. Say you have two servers, ``x``, and ``y`` that handles regular tasks,
  333. and one server ``z``, that only handles feed related tasks, you can use this
  334. configuration:
  335. * Servers ``x`` and ``y``: settings.py:
  336. .. code-block:: python
  337. CELERY_DEFAULT_QUEUE = "regular_tasks"
  338. CELERY_QUEUES = {
  339. "regular_tasks": {
  340. "binding_key": "task.#",
  341. },
  342. }
  343. CELERY_DEFAULT_EXCHANGE = "tasks"
  344. CELERY_DEFAULT_EXCHANGE_TYPE = "topic"
  345. CELERY_DEFAULT_ROUTING_KEY = "task.regular"
  346. * Server ``z``: settings.py:
  347. .. code-block:: python
  348. CELERY_DEFAULT_QUEUE = "feed_tasks"
  349. CELERY_QUEUES = {
  350. "feed_tasks": {
  351. "binding_key": "feed.#",
  352. },
  353. }
  354. CELERY_DEFAULT_EXCHANGE = "tasks"
  355. CELERY_DEFAULT_ROUTING_KEY = "task.regular"
  356. CELERY_DEFAULT_EXCHANGE_TYPE = "topic"
  357. ``CELERY_QUEUES`` is a map of queue names and their exchange/type/binding_key,
  358. if you don't set exchange or exchange type, they will be taken from the
  359. ``CELERY_DEFAULT_EXCHANGE``/``CELERY_DEFAULT_EXCHANGE_TYPE`` settings.
  360. Now to make a Task run on the ``z`` server you need to set its
  361. ``routing_key`` attribute so it starts with the words ``"task.feed."``:
  362. .. code-block:: python
  363. from feedaggregator.models import Feed
  364. from celery.decorators import task
  365. @task(routing_key="feed.importer")
  366. def import_feed(feed_url):
  367. Feed.objects.import_feed(feed_url)
  368. or if subclassing the ``Task`` class directly:
  369. .. code-block:: python
  370. class FeedImportTask(Task):
  371. routing_key = "feed.importer"
  372. def run(self, feed_url):
  373. Feed.objects.import_feed(feed_url)
  374. You can also override this using the ``routing_key`` argument to
  375. :func:`celery.task.apply_async`:
  376. >>> from myapp.tasks import RefreshFeedTask
  377. >>> RefreshFeedTask.apply_async(args=["http://cnn.com/rss"],
  378. ... routing_key="feed.importer")
  379. If you want, you can even have your feed processing worker handle regular
  380. tasks as well, maybe in times when there's a lot of work to do.
  381. Just add a new queue to server ``z``'s ``CELERY_QUEUES``:
  382. .. code-block:: python
  383. CELERY_QUEUES = {
  384. "feed_tasks": {
  385. "binding_key": "feed.#",
  386. },
  387. "regular_tasks": {
  388. "binding_key": "task.#",
  389. },
  390. }
  391. Since the default exchange is ``tasks``, they will both use the same
  392. exchange.
  393. If you have another queue but on another exchange you want to add,
  394. just specify a custom exchange and exchange type:
  395. .. code-block:: python
  396. CELERY_QUEUES = {
  397. "feed_tasks": {
  398. "binding_key": "feed.#",
  399. },
  400. "regular_tasks": {
  401. "binding_key": "task.#",
  402. }
  403. "image_tasks": {
  404. "binding_key": "image.compress",
  405. "exchange": "mediatasks",
  406. "exchange_type": "direct",
  407. },
  408. }
  409. If you're confused about these terms, you should read up on AMQP and RabbitMQ.
  410. `Rabbits and Warrens`_ is an excellent blog post describing queues and
  411. exchanges. There's also AMQP in 10 minutes*: `Flexible Routing Model`_,
  412. and `Standard Exchange Types`_. For users of RabbitMQ the `RabbitMQ FAQ`_
  413. could also be useful as a source of information.
  414. .. _`Rabbits and Warrens`: http://blogs.digitar.com/jjww/2009/01/rabbits-and-warrens/
  415. .. _`Flexible Routing Model`: http://bit.ly/95XFO1
  416. .. _`Standard Exchange Types`: http://bit.ly/EEWca
  417. .. _`RabbitMQ FAQ`: http://www.rabbitmq.com/faq.html
  418. Can I use celery without Django?
  419. --------------------------------
  420. **Answer:** Yes.
  421. Celery uses something called loaders to read/setup configuration, import
  422. modules that register tasks and to decide what happens when a task is
  423. executed. Currently there are two loaders, the default loader and the Django
  424. loader. If you want to use celery without a Django project, you either have to
  425. use the default loader, or write a loader of your own.
  426. The rest of this answer describes how to use the default loader.
  427. While it is possible to use Celery from outside of Django, we still need
  428. Django itself to run, this is to use the ORM and cache-framework.
  429. Duplicating these features would be time consuming and mostly pointless, so
  430. while me might rewrite these in the future, this is a good solution in the
  431. mean time.
  432. Install Django using your favorite install tool, ``easy_install``, ``pip``, or
  433. whatever::
  434. # easy_install django # as root
  435. You need a configuration file named ``celeryconfig.py``, either in the
  436. directory you run ``celeryd`` in, or in a Python library path where it is
  437. able to find it. The configuration file can contain any of the settings
  438. described in :mod:`celery.conf`. In addition; if you're using the
  439. database backend you have to configure the database. Here is an example
  440. configuration using the database backend with MySQL:
  441. .. code-block:: python
  442. # Broker configuration
  443. BROKER_HOST = "localhost"
  444. BROKER_PORT = "5672"
  445. BROKER_VHOST = "celery"
  446. BROKER_USER = "celery"
  447. BROKER_PASSWORD = "celerysecret"
  448. CARROT_BACKEND="amqp"
  449. # Using the database backend.
  450. CELERY_RESULT_BACKEND = "database"
  451. DATABASE_ENGINE = "mysql" # see Django docs for a description of these.
  452. DATABASE_NAME = "mydb"
  453. DATABASE_HOST = "mydb.example.org"
  454. DATABASE_USER = "myuser"
  455. DATABASE_PASSWORD = "mysecret"
  456. # Number of processes that processes tasks simultaneously.
  457. CELERYD_CONCURRENCY = 8
  458. # Modules to import when celeryd starts.
  459. # This must import every module where you register tasks so celeryd
  460. # is able to find and run them.
  461. CELERY_IMPORTS = ("mytaskmodule1", "mytaskmodule2")
  462. With this configuration file in the current directory you have to
  463. run ``celeryinit`` to create the database tables::
  464. $ celeryinit
  465. At this point you should be able to successfully run ``celeryd``::
  466. $ celeryd --loglevel=INFO
  467. and send a task from a python shell (note that it must be able to import
  468. ``celeryconfig.py``):
  469. >>> from celery.task.builtins import PingTask
  470. >>> result = PingTask.apply_async()
  471. >>> result.get()
  472. 'pong'
  473. The celery test-suite is failing
  474. --------------------------------
  475. **Answer**: If you're running tests from your Django project, and the celery
  476. test suite is failing in that context, then follow the steps below. If the
  477. celery tests are failing in another context, please report an issue to our
  478. issue tracker at GitHub:
  479. http://github.com/ask/celery/issues/
  480. That Django is running tests for all applications in ``INSTALLED_APPS``
  481. by default is a pet peeve for many. You should use a test runner that either
  482. 1) Explicitly lists the apps you want to run tests for, or
  483. 2) Make a test runner that skips tests for apps you don't want to run.
  484. For example the test runner that celery is using:
  485. http://bit.ly/NVKep
  486. To use this test runner, add the following to your ``settings.py``:
  487. .. code-block:: python
  488. TEST_RUNNER = "celery.tests.runners.run_tests"
  489. TEST_APPS = (
  490. "app1",
  491. "app2",
  492. "app3",
  493. "app4",
  494. )
  495. Or, if you just want to skip the celery tests:
  496. .. code-block:: python
  497. INSTALLED_APPS = (.....)
  498. TEST_RUNNER = "celery.tests.runners.run_tests"
  499. TEST_APPS = filter(lambda k: k != "celery", INSTALLED_APPS)
  500. Can I change the interval of a periodic task at runtime?
  501. --------------------------------------------------------
  502. **Answer**: Yes. You can override ``PeriodicTask.is_due`` or turn
  503. ``PeriodicTask.run_every`` into a property:
  504. .. code-block:: python
  505. class MyPeriodic(PeriodicTask):
  506. def run(self):
  507. # ...
  508. @property
  509. def run_every(self):
  510. return get_interval_from_database(...)
  511. Does celery support task priorities?
  512. ------------------------------------
  513. **Answer**: No. In theory, yes, as AMQP supports priorities. However
  514. RabbitMQ doesn't implement them yet.
  515. The usual way to prioritize work in celery, is to route high priority tasks
  516. to different servers. In the real world this may actually work better than per message
  517. priorities. You can use this in combination with rate limiting to achieve a
  518. highly performant system.
  519. Can I schedule tasks to execute at a specific time?
  520. ---------------------------------------------------
  521. .. module:: celery.task.base
  522. **Answer**: Yes. You can use the ``eta`` argument of :meth:`Task.apply_async`.
  523. Or to schedule a periodic task at a specific time, use the
  524. :class:`celery.task.schedules.crontab` schedule behavior:
  525. .. code-block:: python
  526. from celery.task.schedules import crontab
  527. from celery.decorators import periodic_task
  528. @periodic_task(run_every=crontab(hours=7, minute=30, day_of_week="mon"))
  529. def every_monday_morning():
  530. print("This is run every monday morning at 7:30")
  531. How do I shut down ``celeryd`` safely?
  532. --------------------------------------
  533. **Answer**: Use the ``TERM`` signal, and celery will finish all currently
  534. executing jobs and shut down as soon as possible. No tasks should be lost.
  535. You should never stop ``celeryd`` with the ``KILL`` signal (``-9``),
  536. unless you've tried ``TERM`` a few times and waited a few minutes to let it
  537. get a chance to shut down. As if you do tasks may be terminated mid-execution,
  538. and they will not be re-run unless you have the ``acks_late`` option set.
  539. (``Task.acks_late`` / ``CELERY_ACKS_LATE``).
  540. How do I run celeryd in the background on [platform]?
  541. -----------------------------------------------------
  542. **Answer**: Please see :doc:`cookbook/daemonizing`.
  543. Django
  544. ======
  545. Generating a template in a task doesn't seem to respect my i18n settings?
  546. -------------------------------------------------------------------------
  547. **Answer**: To enable the Django translation machinery you need to activate
  548. it with a language. **Note**: Be sure to reset to the previous language when
  549. done.
  550. >>> from django.utils import translation
  551. >>> prev_language = translation.get_language()
  552. >>> translation.activate(language)
  553. >>> try:
  554. ... render_template()
  555. ... finally:
  556. translation.activate(prev_language)
  557. The common pattern here would be for the task to take a ``language``
  558. argument:
  559. .. code-block:: python
  560. from celery.decorators import task
  561. from django.utils import translation
  562. from django.template.loader import render_to_string
  563. @task()
  564. def generate_report(template="report.html", language=None):
  565. prev_language = translation.get_language()
  566. language and translation.activate(language)
  567. try:
  568. report = render_to_string(template)
  569. finally:
  570. translation.activate(prev_language)
  571. save_report_somewhere(report)