FAQ 26 KB

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