FAQ 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  1. ============================
  2. Frequently Asked Questions
  3. ============================
  4. General
  5. =======
  6. What kinds of things should I use celery for
  7. --------------------------------------------
  8. **Answer:** Anything asynchronous.
  9. fixme: long answer with some examples of sensible uses goes here
  10. Misconceptions
  11. ==============
  12. Is celery dependent on pickle?
  13. ------------------------------
  14. **Answer:** No.
  15. Celery can support any serialization scheme and has support for JSON/YAML and
  16. Pickle by default. You can even send one task using pickle, and another one
  17. with JSON seamlessly, this is because every task is associated with a
  18. content-type. The default serialization scheme is pickle because it's the most
  19. used, and it has support for sending complex objects as task arguments.
  20. You can set a global default serializer, the default serializer for a
  21. particular Task, or even what serializer to use when sending a single task
  22. instance.
  23. Is celery for Django only?
  24. --------------------------
  25. **Answer:** No.
  26. While django itself is a dependency, you can still use all of celery's features
  27. outside of a django project. fixme: question about removing the dependency
  28. Do I have to use AMQP/RabbitMQ?
  29. -------------------------------
  30. **Answer**: No.
  31. You can also use Redis or an SQL database, see `Using other
  32. queues`_.
  33. .. _`Using other queues`:
  34. http://ask.github.com/celery/tutorials/otherqueues.html
  35. Redis or a database won't perform as well as
  36. an AMQP broker. If you have strict reliability requirements you are
  37. encouraged to use RabbitMQ or another AMQP broker. Redis/database also use
  38. polling, so they are likely to consume more resources. However, if you for
  39. some reason are not able to use AMQP, feel free to use these alternatives.
  40. They will probably work fine for most use cases, and note that the above
  41. points are not specific to celery; If using Redis/database as a queue worked
  42. fine for you before, it probably will now. You can always upgrade later
  43. if you need to.
  44. Is celery multi-lingual?
  45. ------------------------
  46. **Answer:** Yes.
  47. celeryd is an implementation of celery in python. If the language has an AMQP
  48. client, there shouldn't be much work to create a worker in your language.
  49. A celery worker is just a program connecting to the broker to consume
  50. messages. There's no other communication involved.
  51. Also, there's another way to be language indepedent, and that is to use REST
  52. tasks, instead of your tasks being functions, they're URLs. With this
  53. information you can even create simple web servers that enable preloading of
  54. code. See: `User Guide: Remote Tasks`_.
  55. .. _`User Guide: Remote Tasks`:
  56. http://ask.github.com/celery/userguide/remote-tasks.html
  57. Troubleshooting
  58. ===============
  59. MySQL is throwing deadlock errors, what can I do?
  60. -------------------------------------------------
  61. **Answer:** MySQL has default isolation level set to ``REPEATABLE-READ``,
  62. if you don't really need that, set it to ``READ-COMMITTED``.
  63. You can do that by adding the following to your ``my.cnf``::
  64. [mysqld]
  65. transaction-isolation = READ-COMMITTED
  66. For more information about InnoDBs transaction model see `MySQL - The InnoDB
  67. Transaction Model and Locking`_ in the MySQL user manual.
  68. (Thanks to Honza Kral and Anton Tsigularov for this solution)
  69. .. _`MySQL - The InnoDB Transaction Model and Locking`: http://dev.mysql.com/doc/refman/5.1/en/innodb-transaction-model.html
  70. celeryd is not doing anything, just hanging
  71. --------------------------------------------
  72. **Answer:** See `MySQL is throwing deadlock errors, what can I do?`_.
  73. or `Why is Task.delay/apply\* just hanging?`.
  74. Why is Task.delay/apply\*/celeryd just hanging?
  75. -----------------------------------------------
  76. **Answer:** There is a bug in some AMQP clients that will make it hang if
  77. it's not able to authenticate the current user, the password doesn't match or
  78. the user does not have access to the virtual host specified. Be sure to check
  79. your broker logs (for RabbitMQ that is ``/var/log/rabbitmq/rabbit.log`` on
  80. most systems), it usually contains a message describing the reason.
  81. Why won't celeryd run on FreeBSD?
  82. ---------------------------------
  83. **Answer:** multiprocessing.Pool requires a working POSIX semaphore
  84. implementation which isn't enabled in FreeBSD by default. You have to enable
  85. POSIX semaphores in the kernel and manually recompile multiprocessing.
  86. Luckily, Viktor Petersson has written a tutorial to get you started with
  87. Celery on FreeBSD here:
  88. http://www.playingwithwire.com/2009/10/how-to-get-celeryd-to-work-on-freebsd/
  89. I'm having ``IntegrityError: Duplicate Key`` errors. Why?
  90. ----------------------------------------------------------
  91. **Answer:** See `MySQL is throwing deadlock errors, what can I do?`_.
  92. Thanks to howsthedotcom.
  93. Why aren't my tasks processed?
  94. -----------------------------
  95. **Answer:** With RabbitMQ you can see how many consumers are currently
  96. receiving tasks by running the following command::
  97. $ rabbitmqctl list_queues -p <myvhost> name messages consumers
  98. Listing queues ...
  99. celery 2891 2
  100. This shows that there's 2891 messages waiting to be processed in the task
  101. queue, and there are two consumers processing them.
  102. One reason that the queue is never emptied could be that you have a stale
  103. celery process taking the messages hostage. This could happen if celeryd
  104. wasn't properly shut down.
  105. When a message is recieved by a worker the broker waits for it to be
  106. acknowledged before marking the message as processed. The broker will not
  107. re-send that message to another consumer until the consumer is shut down
  108. properly.
  109. If you hit this problem you have to kill all workers manually and restart
  110. them::
  111. ps auxww | grep celeryd | awk '{print $2}' | xargs kill
  112. You might have to wait a while until all workers have finished the work they're
  113. doing. If it's still hanging after a long time you can kill them by force
  114. with::
  115. ps auxww | grep celeryd | awk '{print $2}' | xargs kill -9
  116. fixme: killall wont work?
  117. Why won't my Task run?
  118. ----------------------
  119. **Answer:** Did you register the task in the applications ``tasks.py`` module?
  120. (or in some other module Django loads by default, like ``models.py``?).
  121. Also there might be syntax errors preventing the tasks module being imported.
  122. You can find out if celery is able to run the task by executing the
  123. task manually:
  124. >>> from myapp.tasks import MyPeriodicTask
  125. >>> MyPeriodicTask.delay()
  126. Watch celeryds logfile to see if it's able to find the task, or if some
  127. other error is happening.
  128. Why won't my Periodic Task run?
  129. -------------------------------
  130. **Answer:** See `Why won't my Task run?`_.
  131. How do I discard all waiting tasks?
  132. ------------------------------------
  133. **Answer:** Use ``celery.task.discard_all()``, like this:
  134. >>> from celery.task import discard_all
  135. >>> discard_all()
  136. 1753
  137. The number ``1753`` is the number of messages deleted.
  138. You can also start celeryd with the ``--discard`` argument which will
  139. accomplish the same thing.
  140. I've discarded messages, but there are still messages left in the queue?
  141. ------------------------------------------------------------------------
  142. **Answer:** Tasks are acknowledged (removed from the queue) as soon
  143. as they are actually executed. After the worker has received a task, it will
  144. take some time until it is actually executed, especially if there are a lot
  145. of tasks already waiting for execution. Messages that are not acknowledged are
  146. hold on to by the worker until it closes the connection to the broker (AMQP
  147. server). When that connection is closed (e.g because the worker was stopped)
  148. the tasks will be re-sent by the broker to the next available worker (or the
  149. same worker when it has been restarted), so to properly purge the queue of
  150. waiting tasks you have to stop all the workers, and then discard the tasks
  151. using ``discard_all``.
  152. Brokers
  153. =======
  154. Can I use celery with ActiveMQ/STOMP?
  155. -------------------------------------
  156. **Answer**: Yes, but this is somewhat experimental for now.
  157. It is working ok in a test configuration, but it has not
  158. been tested in production like RabbitMQ has. If you have any problems with
  159. using STOMP and celery, please report the bugs to the issue tracker:
  160. http://github.com/ask/celery/issues/
  161. First you have to use the ``master`` branch of ``celery``::
  162. $ git clone git://github.com/ask/celery.git
  163. $ cd celery
  164. $ sudo python setup.py install
  165. $ cd ..
  166. Then you need to install the ``stompbackend`` branch of ``carrot``::
  167. $ git clone git://github.com/ask/carrot.git
  168. $ cd carrot
  169. $ git checkout stompbackend
  170. $ sudo python setup.py install
  171. $ cd ..
  172. And my fork of ``python-stomp`` which adds non-blocking support::
  173. $ hg clone http://bitbucket.org/asksol/python-stomp/
  174. $ cd python-stomp
  175. $ sudo python setup.py install
  176. $ cd ..
  177. In this example we will use a queue called ``celery`` which we created in
  178. the ActiveMQ web admin interface.
  179. **Note**: For ActiveMQ the queue name has to have ``"/queue/"`` prepended to
  180. it. i.e. the queue ``celery`` becomes ``/queue/celery``.
  181. Since a STOMP queue is a single named entity and it doesn't have the
  182. routing capabilities of AMQP you need to set both the ``queue``, and
  183. ``exchange`` settings to your queue name. This is a minor inconvenience since
  184. carrot needs to maintain the same interface for both AMQP and STOMP (obviously
  185. the one with the most capabilities won).
  186. Use the following specific settings in your ``settings.py``:
  187. .. code-block:: python
  188. # Makes python-stomp the default backend for carrot.
  189. CARROT_BACKEND = "stomp"
  190. # STOMP hostname and port settings.
  191. BROKER_HOST = "localhost"
  192. BROKER_PORT = 61613
  193. # The queue name to use (both queue and exchange must be set to the
  194. # same queue name when using STOMP)
  195. CELERY_DEFAULT_QUEUE = "/queue/celery"
  196. CELERY_DEFAULT_EXCHANGE = "/queue/celery"
  197. CELERY_QUEUES = {
  198. "/queue/celery": {"exchange": "/queue/celery"}
  199. }
  200. Now you can go on reading the tutorial in the README, ignoring any AMQP
  201. specific options.
  202. What features are not supported when using STOMP?
  203. --------------------------------------------------
  204. This is a (possible incomplete) list of features not available when
  205. using the STOMP backend:
  206. * routing keys
  207. * exchange types (direct, topic, headers, etc)
  208. * immediate
  209. * mandatory
  210. Features
  211. ========
  212. Can I send some tasks to only some servers?
  213. --------------------------------------------
  214. **Answer:** Yes. You can route tasks to an arbitrary server using AMQP,
  215. and a worker can bind to as many queues as it wants.
  216. Say you have two servers, ``x``, and ``y`` that handles regular tasks,
  217. and one server ``z``, that only handles feed related tasks, you can use this
  218. configuration:
  219. * Servers ``x`` and ``y``: settings.py:
  220. .. code-block:: python
  221. CELERY_DEFAULT_QUEUE = "regular_tasks"
  222. CELERY_QUEUES = {
  223. "regular_tasks": {
  224. "binding_key": "task.#",
  225. },
  226. }
  227. CELERY_DEFAULT_EXCHANGE = "tasks"
  228. CELERY_DEFAULT_EXCHANGE_TYPE = "topic"
  229. CELERY_DEFAULT_ROUTING_KEY = "task.regular"
  230. * Server ``z``: settings.py:
  231. .. code-block:: python
  232. CELERY_DEFAULT_QUEUE = "feed_tasks"
  233. CELERY_QUEUES = {
  234. "feed_tasks": {
  235. "binding_key": "feed.#",
  236. },
  237. }
  238. CELERY_DEFAULT_EXCHANGE = "tasks"
  239. CELERY_DEFAULT_ROUTING_KEY = "task.regular"
  240. CELERY_DEFAULT_EXCHANGE_TYPE = "topic"
  241. ``CELERY_QUEUES`` is a map of queue names and their exchange/type/binding_key,
  242. if you don't set exchange or exchange type, they will be taken from the
  243. ``CELERY_DEFAULT_EXCHANGE``/``CELERY_DEFAULT_EXCHANGE_TYPE`` settings.
  244. Now to make a Task run on the ``z`` server you need to set its
  245. ``routing_key`` attribute so it starts with the words ``"task.feed."``:
  246. .. code-block:: python
  247. from feedaggregator.models import Feed
  248. from celery.decorators import task
  249. @task(routing_key="feed.importer")
  250. def import_feed(feed_url):
  251. Feed.objects.import_feed(feed_url)
  252. or if subclassing the ``Task`` class directly:
  253. .. code-block:: python
  254. class FeedImportTask(Task):
  255. routing_key = "feed.importer"
  256. def run(self, feed_url):
  257. Feed.objects.import_feed(feed_url)
  258. You can also override this using the ``routing_key`` argument to
  259. :func:`celery.task.apply_async`:
  260. >>> from myapp.tasks import RefreshFeedTask
  261. >>> RefreshFeedTask.apply_async(args=["http://cnn.com/rss"],
  262. ... routing_key="feed.importer")
  263. If you want, you can even have your feed processing worker handle regular
  264. tasks as well, maybe in times when there's a lot of work to do.
  265. Just add a new queue to server ``z``'s ``CELERY_QUEUES``:
  266. .. code-block:: python
  267. CELERY_QUEUES = {
  268. "feed_tasks": {
  269. "binding_key": "feed.#",
  270. },
  271. "regular_tasks": {
  272. "binding_key": "task.#",
  273. },
  274. }
  275. Since the default exchange is ``tasks``, they will both use the same
  276. exchange.
  277. If you have another queue but on another exchange you want to add,
  278. just specify a custom exchange and exchange type:
  279. .. code-block:: python
  280. CELERY_QUEUES = {
  281. "feed_tasks": {
  282. "binding_key": "feed.#",
  283. },
  284. "regular_tasks": {
  285. "binding_key": "task.#",
  286. }
  287. "image_tasks": {
  288. "binding_key": "image.compress",
  289. "exchange": "mediatasks",
  290. "exchange_type": "direct",
  291. },
  292. }
  293. Easy? No? If you're confused about these terms, you should read up on
  294. AMQP and RabbitMQ. It might be hard to grok the concepts of
  295. queues, exchanges and routing/binding keys at first, but it's all very simple,
  296. I assure you. fixme: too colloquial perhaps? Maybe add links to docs
  297. Can I use celery without Django?
  298. --------------------------------
  299. **Answer:** Yes.
  300. Celery uses something called loaders to read/setup configuration, import
  301. modules that register tasks and to decide what happens when a task is
  302. executed. Currently there are two loaders, the default loader and the Django
  303. loader. If you want to use celery without a Django project, you either have to
  304. use the default loader, or write a loader of your own.
  305. The rest of this answer describes how to use the default loader.
  306. First of all, installation. You need to get the development version of
  307. celery from github:: fixme: even in 1.0?
  308. $ git clone git://github.com/ask/celery.git
  309. $ cd celery
  310. # python setup.py install # as root
  311. While it is possible to use celery from outside of Django, we still need
  312. Django itself to run, this is to use the ORM and cache-framework, etc.
  313. Duplicating these features would be time consuming and mostly pointless, so
  314. we decided that having a dependency on Django itself was a good thing.
  315. Install Django using your favorite install tool, ``easy_install``, ``pip``, or
  316. whatever::
  317. # easy_install django # as root
  318. You need a configuration file named ``celeryconfig.py``, either in the
  319. directory you run ``celeryd`` in, or in a Python library path where it is
  320. able to find it. The configuration file can contain any of the settings
  321. described in :mod:`celery.conf`. In addition; if you're using the
  322. database backend you have to configure the database. Here is an example
  323. configuration using the database backend with MySQL:
  324. .. code-block:: python
  325. # Broker configuration
  326. BROKER_HOST = "localhost"
  327. BROKER_PORT = "5672"
  328. BROKER_VHOST = "celery"
  329. BROKER_USER = "celery"
  330. BROKER_PASSWORD = "celerysecret"
  331. CARROT_BACKEND="amqp"
  332. # Using the database backend.
  333. CELERY_BACKEND = "database"
  334. DATABASE_ENGINE = "mysql" # see Django docs for a description of these.
  335. DATABASE_NAME = "mydb"
  336. DATABASE_HOST = "mydb.example.org"
  337. DATABASE_USER = "myuser"
  338. DATABASE_PASSWORD = "mysecret"
  339. # Number of processes that processes tasks simultaneously.
  340. CELERYD_CONCURRENCY = 8
  341. # Modules to import when celeryd starts.
  342. # This must import every module where you register tasks so celeryd
  343. # is able to find and run them.
  344. CELERY_IMPORTS = ("mytaskmodule1", "mytaskmodule2")
  345. With this configuration file in the current directory you have to
  346. run ``celeryinit`` to create the database tables::
  347. $ celeryinit
  348. At this point you should be able to successfully run ``celeryd``::
  349. $ celeryd --loglevel=INFO
  350. and send a task from a python shell (note that it must be able to import
  351. ``celeryconfig.py``):
  352. >>> from celery.task.builtins import PingTask
  353. >>> result = PingTask.apply_async()
  354. >>> result.get()
  355. 'pong'
  356. The celery test-suite is failing
  357. --------------------------------
  358. **Answer**: You're running tests from your own Django applicaiton, and celery's
  359. tests are failing and celery's tests are failing in that context? fixme: I don't get the preceding sentence
  360. If so, read on for a trick, if not please report the test failure to our issue
  361. tracker on GitHub.
  362. http://github.com/ask/celery/issues/
  363. That Django is running tests for all applications in ``INSTALLED_APPS``
  364. is a pet peeve of mine. You should use a test runner that either
  365. 1) Explicitly lists the apps you want to run tests for, or:
  366. 2) Make a test runner that skips tests for apps you don't want to run.
  367. For example this test runner that celery is using:
  368. http://bit.ly/NVKep
  369. To use this add the following to your settings.py:
  370. .. code-block:: python
  371. TEST_RUNNER = "celery.tests.runners.run_tests"
  372. TEST_APPS = (
  373. "app1",
  374. "app2",
  375. "app3",
  376. "app4",
  377. )
  378. If you just want to skip celery you could use:
  379. .. code-block:: python
  380. INSTALLED_APPS = (.....)
  381. TEST_RUNNER = "celery.tests.runners.run_tests"
  382. TEST_APPS = filter(lambda k: k != "celery", INSTALLED_APPS)
  383. Can I change the interval of a periodic task at runtime?
  384. --------------------------------------------------------
  385. **Answer**: Yes. You can override ``PeriodicTask.is_due`` or turn
  386. ``PeriodicTask.run_every`` into a property:
  387. .. code-block:: python
  388. class MyPeriodic(PeriodicTask):
  389. def run(self):
  390. # ...
  391. @property
  392. def run_every(self):
  393. return get_interval_from_database(...)
  394. Does celery support task priorities?
  395. ------------------------------------
  396. **Answer**: No. In theory, yes, as AMQP supports priorities. However
  397. RabbitMQ doesn't implement them yet.
  398. The usual way to prioritize work in celery, is to route high priority tasks
  399. to different servers. In the real world this may actually work better than per message
  400. priorities. You can use this in combination with rate limiting to achieve a
  401. highly performant system.
  402. Can I schedule tasks to execute at a specific time?
  403. ---------------------------------------------------
  404. .. module:: celery.task.base
  405. **Answer**: Yes. You can use the ``eta`` argument of :meth:`Task.apply_async`.
  406. However, you can't schedule a periodic task at a specific time yet.
  407. The good news is, if anyone is willing
  408. to implement it, it shouldn't be that hard. Some pointers to achieve this has
  409. been written here: http://bit.ly/99UQNO
  410. How do I shut down ``celeryd`` safely?
  411. --------------------------------------
  412. **Answer**: Use the ``TERM`` signal, and celery will finish all currently
  413. executing jobs and shut down as soon as possible. No tasks should be lost.
  414. You should never stop ``celeryd`` with the ``KILL`` signal (``-9``),
  415. unless you've tried ``TERM`` a few times and waited a few minutes to let it
  416. get a chance to shut down.