tasks.rst 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414
  1. .. _guide-tasks:
  2. =======
  3. Tasks
  4. =======
  5. Tasks are the building blocks of Celery applications.
  6. A task is a class that can be created out of any callable. It performs
  7. dual roles in that it defines both what happens when a task is
  8. called (sends a message), and what happens when a worker receives that message.
  9. Every task class has a unique name, and this name is referenced in messages
  10. so that the worker can find the right function to execute.
  11. A task message does not disappear
  12. until the message has been :term:`acknowledged` by a worker. A worker can reserve
  13. many messages in advance and even if the worker is killed -- caused by power failure
  14. or otherwise -- the message will be redelivered to another worker.
  15. Ideally task functions should be :term:`idempotent`, which means that
  16. the function will not cause unintented effects even if called
  17. multiple times with the same arguments.
  18. Since the worker cannot detect if your tasks are idempotent, the default
  19. behavior is to acknowledge the message in advance, before it's executed,
  20. so that a task that has already been started is never executed again..
  21. If your task is idempotent you can set the :attr:`acks_late` option
  22. to have the worker acknowledge the message *after* the task returns
  23. instead. See also the FAQ entry :ref:`faq-acks_late-vs-retry`.
  24. --
  25. In this chapter you will learn all about defining tasks,
  26. and this is the **table of contents**:
  27. .. contents::
  28. :local:
  29. :depth: 1
  30. .. _task-basics:
  31. Basics
  32. ======
  33. You can easily create a task from any callable by using
  34. the :meth:`~@Celery.task` decorator:
  35. .. code-block:: python
  36. from .models import User
  37. @app.task
  38. def create_user(username, password):
  39. User.objects.create(username=username, password=password)
  40. There are also many :ref:`options <task-options>` that can be set for the task,
  41. these can be specified as arguments to the decorator:
  42. .. code-block:: python
  43. @app.task(serializer='json')
  44. def create_user(username, password):
  45. User.objects.create(username=username, password=password)
  46. .. sidebar:: How do I import the task decorator? And what is "app"?
  47. The task decorator is available on your :class:`@Celery` application instance,
  48. if you don't know what that is then please read :ref:`first-steps`.
  49. If you're using Django or are still using the "old" module based celery API,
  50. then you can import the task decorator like this::
  51. from celery import task
  52. @task
  53. def add(x, y):
  54. return x + y
  55. .. sidebar:: Multiple decorators
  56. When using multiple decorators in combination with the task
  57. decorator you must make sure that the `task`
  58. decorator is applied last (which in Python oddly means that it must
  59. be the first in the list):
  60. .. code-block:: python
  61. @app.task
  62. @decorator2
  63. @decorator1
  64. def add(x, y):
  65. return x + y
  66. .. _task-names:
  67. Names
  68. =====
  69. Every task must have a unique name, and a new name
  70. will be generated out of the function name if a custom name is not provided.
  71. For example:
  72. .. code-block:: python
  73. >>> @app.task(name='sum-of-two-numbers')
  74. >>> def add(x, y):
  75. ... return x + y
  76. >>> add.name
  77. 'sum-of-two-numbers'
  78. A best practice is to use the module name as a namespace,
  79. this way names won't collide if there's already a task with that name
  80. defined in another module.
  81. .. code-block:: python
  82. >>> @app.task(name='tasks.add')
  83. >>> def add(x, y):
  84. ... return x + y
  85. You can tell the name of the task by investigating its name attribute::
  86. >>> add.name
  87. 'tasks.add'
  88. Which is exactly the name that would have been generated anyway,
  89. if the module name is "tasks.py":
  90. :file:`tasks.py`:
  91. .. code-block:: python
  92. @app.task
  93. def add(x, y):
  94. return x + y
  95. >>> from tasks import add
  96. >>> add.name
  97. 'tasks.add'
  98. .. _task-naming-relative-imports:
  99. Automatic naming and relative imports
  100. -------------------------------------
  101. Relative imports and automatic name generation does not go well together,
  102. so if you're using relative imports you should set the name explicitly.
  103. For example if the client imports the module "myapp.tasks" as ".tasks", and
  104. the worker imports the module as "myapp.tasks", the generated names won't match
  105. and an :exc:`~@NotRegistered` error will be raised by the worker.
  106. This is also the case if using Django and using `project.myapp`::
  107. INSTALLED_APPS = ('project.myapp', )
  108. The worker will have the tasks registered as "project.myapp.tasks.*",
  109. while this is what happens in the client if the module is imported as
  110. "myapp.tasks":
  111. .. code-block:: python
  112. >>> from myapp.tasks import add
  113. >>> add.name
  114. 'myapp.tasks.add'
  115. For this reason you should never use "project.app", but rather
  116. add the project directory to the Python path::
  117. import os
  118. import sys
  119. sys.path.append(os.path.dirname(os.path.basename(__file__)))
  120. INSTALLED_APPS = ('myapp', )
  121. This makes more sense from the reusable app perspective anyway.
  122. .. _task-request-info:
  123. Context
  124. =======
  125. :attr:`~@Task.request` contains information and state related to
  126. the executing task.
  127. The request defines the following attributes:
  128. :id: The unique id of the executing task.
  129. :group: The unique id a group, if this task is a member.
  130. :chord: The unique id of the chord this task belongs to (if the task
  131. is part of the header).
  132. :args: Positional arguments.
  133. :kwargs: Keyword arguments.
  134. :retries: How many times the current task has been retried.
  135. An integer starting at `0`.
  136. :is_eager: Set to :const:`True` if the task is executed locally in
  137. the client, and not by a worker.
  138. :eta: The original ETA of the task (if any).
  139. This is in UTC time (depending on the :setting:`CELERY_ENABLE_UTC`
  140. setting).
  141. :expires: The original expiry time of the task (if any).
  142. This is in UTC time (depending on the :setting:`CELERY_ENABLE_UTC`
  143. setting).
  144. :logfile: The file the worker logs to. See `Logging`_.
  145. :loglevel: The current log level used.
  146. :hostname: Hostname of the worker instance executing the task.
  147. :delivery_info: Additional message delivery information. This is a mapping
  148. containing the exchange and routing key used to deliver this
  149. task. Used by e.g. :meth:`~@Task.retry`
  150. to resend the task to the same destination queue.
  151. Availability of keys in this dict depends on the
  152. message broker used.
  153. :called_directly: This flag is set to true if the task was not
  154. executed by the worker.
  155. :callbacks: A list of subtasks to be called if this task returns successfully.
  156. :errback: A list of subtasks to be called if this task fails.
  157. :utc: Set to true the caller has utc enabled (:setting:`CELERY_ENABLE_UTC`).
  158. An example task accessing information in the context is:
  159. .. code-block:: python
  160. @app.task(bind=True)
  161. def dump_context(self, x, y):
  162. print('Executing task id {0.id}, args: {0.args!r} kwargs: {0.kwargs!r}'.format(
  163. self.request))
  164. The ``bind`` argument means that the function will be a "bound method" so
  165. that you can access attributes and methods on the task type instance.
  166. .. _task-logging:
  167. Logging
  168. =======
  169. The worker will automatically set up logging for you, or you can
  170. configure logging manually.
  171. A special logger is available named "celery.task", you can inherit
  172. from this logger to automatically get the task name and unique id as part
  173. of the logs.
  174. The best practice is to create a common logger
  175. for all of your tasks at the top of your module:
  176. .. code-block:: python
  177. from celery.utils.log import get_task_logger
  178. logger = get_task_logger(__name__)
  179. @app.task
  180. def add(x, y):
  181. logger.info('Adding {0} + {1}'.format(x, y))
  182. return x + y
  183. Celery uses the standard Python logger library,
  184. for which documentation can be found in the :mod:`logging`
  185. module.
  186. You can also use :func:`print`, as anything written to standard
  187. out/-err will be redirected to logging system (you can disable this,
  188. see :setting:`CELERY_REDIRECT_STDOUTS`).
  189. .. _task-retry:
  190. Retrying
  191. ========
  192. :meth:`~@Task.retry` can be used to re-execute the task,
  193. for example in the event of recoverable errors.
  194. When you call ``retry`` it will send a new message, using the same
  195. task-id, and it will take care to make sure the message is delivered
  196. to the same queue as the originating task.
  197. When a task is retried this is also recorded as a task state,
  198. so that you can track the progress of the task using the result
  199. instance (see :ref:`task-states`).
  200. Here's an example using ``retry``:
  201. .. code-block:: python
  202. @app.task(bind=True)
  203. def send_twitter_status(self, oauth, tweet):
  204. try:
  205. twitter = Twitter(oauth)
  206. twitter.update_status(tweet)
  207. except (Twitter.FailWhaleError, Twitter.LoginError) as exc:
  208. raise self.retry(exc=exc)
  209. .. note::
  210. The :meth:`~@Task.retry` call will raise an exception so any code after the retry
  211. will not be reached. This is the :exc:`~@RetryTaskError`
  212. exception, it is not handled as an error but rather as a semi-predicate
  213. to signify to the worker that the task is to be retried,
  214. so that it can store the correct state when a result backend is enabled.
  215. This is normal operation and always happens unless the
  216. ``throw`` argument to retry is set to :const:`False`.
  217. The bind argument to the task decorator will give access to ``self`` (the
  218. task type instance).
  219. The ``exc`` method is used to pass exception information that is
  220. used in logs, and when storing task results.
  221. Both the exception and the traceback will
  222. be available in the task state (if a result backend is enabled).
  223. If the task has a ``max_retries`` value the current exception
  224. will be re-raised if the max number of retries has been exceeded,
  225. but this will not happen if:
  226. - An ``exc`` argument was not given.
  227. In this case the :exc:`celery.exceptions.MaxRetriesExceeded`
  228. exception will be raised.
  229. - There is no current exception
  230. If there's no original exception to re-raise the ``exc``
  231. argument will be used instead, so:
  232. .. code-block:: python
  233. self.retry(exc=Twitter.LoginError())
  234. will raise the ``exc`` argument given.
  235. .. _task-retry-custom-delay:
  236. Using a custom retry delay
  237. --------------------------
  238. When a task is to be retried, it can wait for a given amount of time
  239. before doing so, and the default delay is defined by the
  240. :attr:`~@Task.default_retry_delay`
  241. attribute. By default this is set to 3 minutes. Note that the
  242. unit for setting the delay is in seconds (int or float).
  243. You can also provide the `countdown` argument to :meth:`~@Task.retry` to
  244. override this default.
  245. .. code-block:: python
  246. @app.task(bind=True, default_retry_delay=30 * 60) # retry in 30 minutes.
  247. def add(x, y):
  248. try:
  249. ...
  250. except Exception as exc:
  251. raise self.retry(exc=exc, countdown=60) # override the default and
  252. # retry in 1 minute
  253. .. _task-options:
  254. List of Options
  255. ===============
  256. The task decorator can take a number of options that change the way
  257. the task behaves, for example you can set the rate limit for a task
  258. using the :attr:`rate_limit` option.
  259. Any keyword argument passed to the task decorator will actually be set
  260. as an attribute of the resulting task class, and this is a list
  261. of the built-in attributes.
  262. General
  263. -------
  264. .. _task-general-options:
  265. .. attribute:: Task.name
  266. The name the task is registered as.
  267. You can set this name manually, or a name will be
  268. automatically generated using the module and class name. See
  269. :ref:`task-names`.
  270. .. attribute:: Task.request
  271. If the task is being executed this will contain information
  272. about the current request. Thread local storage is used.
  273. See :ref:`task-request-info`.
  274. .. attribute:: Task.abstract
  275. Abstract classes are not registered, but are used as the
  276. base class for new task types.
  277. .. attribute:: Task.max_retries
  278. The maximum number of attempted retries before giving up.
  279. If the number of retries exceeds this value a :exc:`~@MaxRetriesExceeded`
  280. exception will be raised. *NOTE:* You have to call :meth:`~@Task.retry`
  281. manually, as it will not automatically retry on exception..
  282. The default value is 3.
  283. A value of :const:`None` will disable the retry limit and the
  284. task will retry forever until it succeeds.
  285. .. attribute:: Task.default_retry_delay
  286. Default time in seconds before a retry of the task
  287. should be executed. Can be either :class:`int` or :class:`float`.
  288. Default is a 3 minute delay.
  289. .. attribute:: Task.rate_limit
  290. Set the rate limit for this task type which limits the number of tasks
  291. that can be run in a given time frame. Tasks will still complete when
  292. a rate limit is in effect, but it may take some time before it's allowed to
  293. start.
  294. If this is :const:`None` no rate limit is in effect.
  295. If it is an integer or float, it is interpreted as "tasks per second".
  296. The rate limits can be specified in seconds, minutes or hours
  297. by appending `"/s"`, `"/m"` or `"/h"` to the value.
  298. Example: `"100/m"` (hundred tasks a minute). Default is the
  299. :setting:`CELERY_DEFAULT_RATE_LIMIT` setting, which if not specified means
  300. rate limiting for tasks is disabled by default.
  301. .. attribute:: Task.time_limit
  302. The hard time limit for this task. If not set then the workers default
  303. will be used.
  304. .. attribute:: Task.soft_time_limit
  305. The soft time limit for this task. If not set then the workers default
  306. will be used.
  307. .. attribute:: Task.ignore_result
  308. Don't store task state. Note that this means you can't use
  309. :class:`~celery.result.AsyncResult` to check if the task is ready,
  310. or get its return value.
  311. .. attribute:: Task.store_errors_even_if_ignored
  312. If :const:`True`, errors will be stored even if the task is configured
  313. to ignore results.
  314. .. attribute:: Task.send_error_emails
  315. Send an email whenever a task of this type fails.
  316. Defaults to the :setting:`CELERY_SEND_TASK_ERROR_EMAILS` setting.
  317. See :ref:`conf-error-mails` for more information.
  318. .. attribute:: Task.ErrorMail
  319. If the sending of error emails is enabled for this task, then
  320. this is the class defining the logic to send error mails.
  321. .. attribute:: Task.serializer
  322. A string identifying the default serialization
  323. method to use. Defaults to the :setting:`CELERY_TASK_SERIALIZER`
  324. setting. Can be `pickle` `json`, `yaml`, or any custom
  325. serialization methods that have been registered with
  326. :mod:`kombu.serialization.registry`.
  327. Please see :ref:`calling-serializers` for more information.
  328. .. attribute:: Task.compression
  329. A string identifying the default compression scheme to use.
  330. Defaults to the :setting:`CELERY_MESSAGE_COMPRESSION` setting.
  331. Can be `gzip`, or `bzip2`, or any custom compression schemes
  332. that have been registered with the :mod:`kombu.compression` registry.
  333. Please see :ref:`calling-compression` for more information.
  334. .. attribute:: Task.backend
  335. The result store backend to use for this task. Defaults to the
  336. :setting:`CELERY_RESULT_BACKEND` setting.
  337. .. attribute:: Task.acks_late
  338. If set to :const:`True` messages for this task will be acknowledged
  339. **after** the task has been executed, not *just before*, which is
  340. the default behavior.
  341. Note that this means the task may be executed twice if the worker
  342. crashes in the middle of execution, which may be acceptable for some
  343. applications.
  344. The global default can be overridden by the :setting:`CELERY_ACKS_LATE`
  345. setting.
  346. .. _task-track-started:
  347. .. attribute:: Task.track_started
  348. If :const:`True` the task will report its status as "started"
  349. when the task is executed by a worker.
  350. The default value is :const:`False` as the normal behaviour is to not
  351. report that level of granularity. Tasks are either pending, finished,
  352. or waiting to be retried. Having a "started" status can be useful for
  353. when there are long running tasks and there is a need to report which
  354. task is currently running.
  355. The host name and process id of the worker executing the task
  356. will be available in the state metadata (e.g. `result.info['pid']`)
  357. The global default can be overridden by the
  358. :setting:`CELERY_TRACK_STARTED` setting.
  359. .. seealso::
  360. The API reference for :class:`~@Task`.
  361. .. _task-states:
  362. States
  363. ======
  364. Celery can keep track of the tasks current state. The state also contains the
  365. result of a successful task, or the exception and traceback information of a
  366. failed task.
  367. There are several *result backends* to choose from, and they all have
  368. different strengths and weaknesses (see :ref:`task-result-backends`).
  369. During its lifetime a task will transition through several possible states,
  370. and each state may have arbitrary metadata attached to it. When a task
  371. moves into a new state the previous state is
  372. forgotten about, but some transitions can be deducted, (e.g. a task now
  373. in the :state:`FAILED` state, is implied to have been in the
  374. :state:`STARTED` state at some point).
  375. There are also sets of states, like the set of
  376. :state:`FAILURE_STATES`, and the set of :state:`READY_STATES`.
  377. The client uses the membership of these sets to decide whether
  378. the exception should be re-raised (:state:`PROPAGATE_STATES`), or whether
  379. the state can be cached (it can if the task is ready).
  380. You can also define :ref:`custom-states`.
  381. .. _task-result-backends:
  382. Result Backends
  383. ---------------
  384. Celery needs to store or send the states somewhere. There are several
  385. built-in backends to choose from: SQLAlchemy/Django ORM, Memcached,
  386. RabbitMQ (amqp), MongoDB, and Redis -- or you can define your own.
  387. No backend works well for every use case.
  388. You should read about the strengths and weaknesses of each backend, and choose
  389. the most appropriate for your needs.
  390. .. seealso::
  391. :ref:`conf-result-backend`
  392. RabbitMQ Result Backend
  393. ~~~~~~~~~~~~~~~~~~~~~~~
  394. The RabbitMQ result backend (amqp) is special as it does not actually *store*
  395. the states, but rather sends them as messages. This is an important difference as it
  396. means that a result *can only be retrieved once*; If you have two processes
  397. waiting for the same result, one of the processes will never receive the
  398. result!
  399. Even with that limitation, it is an excellent choice if you need to receive
  400. state changes in real-time. Using messaging means the client does not have to
  401. poll for new states.
  402. There are several other pitfalls you should be aware of when using the
  403. RabbitMQ result backend:
  404. * Every new task creates a new queue on the server, with thousands of tasks
  405. the broker may be overloaded with queues and this will affect performance in
  406. negative ways. If you're using RabbitMQ then each queue will be a separate
  407. Erlang process, so if you're planning to keep many results simultaneously you
  408. may have to increase the Erlang process limit, and the maximum number of file
  409. descriptors your OS allows.
  410. * Old results will be cleaned automatically, based on the
  411. :setting:`CELERY_TASK_RESULT_EXPIRES` setting. By default this is set to
  412. expire after 1 day: if you have a very busy cluster you should lower
  413. this value.
  414. For a list of options supported by the RabbitMQ result backend, please see
  415. :ref:`conf-amqp-result-backend`.
  416. Database Result Backend
  417. ~~~~~~~~~~~~~~~~~~~~~~~
  418. Keeping state in the database can be convenient for many, especially for
  419. web applications with a database already in place, but it also comes with
  420. limitations.
  421. * Polling the database for new states is expensive, and so you should
  422. increase the polling intervals of operations such as `result.get()`.
  423. * Some databases use a default transaction isolation level that
  424. is not suitable for polling tables for changes.
  425. In MySQL the default transaction isolation level is `REPEATABLE-READ`, which
  426. means the transaction will not see changes by other transactions until the
  427. transaction is committed. It is recommended that you change to the
  428. `READ-COMMITTED` isolation level.
  429. .. _task-builtin-states:
  430. Built-in States
  431. ---------------
  432. .. state:: PENDING
  433. PENDING
  434. ~~~~~~~
  435. Task is waiting for execution or unknown.
  436. Any task id that is not known is implied to be in the pending state.
  437. .. state:: STARTED
  438. STARTED
  439. ~~~~~~~
  440. Task has been started.
  441. Not reported by default, to enable please see :attr:`@Task.track_started`.
  442. :metadata: `pid` and `hostname` of the worker process executing
  443. the task.
  444. .. state:: SUCCESS
  445. SUCCESS
  446. ~~~~~~~
  447. Task has been successfully executed.
  448. :metadata: `result` contains the return value of the task.
  449. :propagates: Yes
  450. :ready: Yes
  451. .. state:: FAILURE
  452. FAILURE
  453. ~~~~~~~
  454. Task execution resulted in failure.
  455. :metadata: `result` contains the exception occurred, and `traceback`
  456. contains the backtrace of the stack at the point when the
  457. exception was raised.
  458. :propagates: Yes
  459. .. state:: RETRY
  460. RETRY
  461. ~~~~~
  462. Task is being retried.
  463. :metadata: `result` contains the exception that caused the retry,
  464. and `traceback` contains the backtrace of the stack at the point
  465. when the exceptions was raised.
  466. :propagates: No
  467. .. state:: REVOKED
  468. REVOKED
  469. ~~~~~~~
  470. Task has been revoked.
  471. :propagates: Yes
  472. .. _custom-states:
  473. Custom states
  474. -------------
  475. You can easily define your own states, all you need is a unique name.
  476. The name of the state is usually an uppercase string. As an example
  477. you could have a look at :mod:`abortable tasks <~celery.contrib.abortable>`
  478. which defines its own custom :state:`ABORTED` state.
  479. Use :meth:`~@Task.update_state` to update a task's state::
  480. @app.task(bind=True)
  481. def upload_files(filenames):
  482. for i, file in enumerate(filenames):
  483. self.update_state(state='PROGRESS',
  484. meta={'current': i, 'total': len(filenames)})
  485. Here I created the state `"PROGRESS"`, which tells any application
  486. aware of this state that the task is currently in progress, and also where
  487. it is in the process by having `current` and `total` counts as part of the
  488. state metadata. This can then be used to create e.g. progress bars.
  489. .. _pickling_exceptions:
  490. Creating pickleable exceptions
  491. ------------------------------
  492. A rarely known Python fact is that exceptions must conform to some
  493. simple rules to support being serialized by the pickle module.
  494. Tasks that raise exceptions that are not pickleable will not work
  495. properly when Pickle is used as the serializer.
  496. To make sure that your exceptions are pickleable the exception
  497. *MUST* provide the original arguments it was instantiated
  498. with in its ``.args`` attribute. The simplest way
  499. to ensure this is to have the exception call ``Exception.__init__``.
  500. Let's look at some examples that work, and one that doesn't:
  501. .. code-block:: python
  502. # OK:
  503. class HttpError(Exception):
  504. pass
  505. # BAD:
  506. class HttpError(Exception):
  507. def __init__(self, status_code):
  508. self.status_code = status_code
  509. # OK:
  510. class HttpError(Exception):
  511. def __init__(self, status_code):
  512. self.status_code = status_code
  513. Exception.__init__(self, status_code) # <-- REQUIRED
  514. So the rule is:
  515. For any exception that supports custom arguments ``*args``,
  516. ``Exception.__init__(self, *args)`` must be used.
  517. There is no special support for *keyword arguments*, so if you
  518. want to preserve keyword arguments when the exception is unpickled
  519. you have to pass them as regular args:
  520. .. code-block:: python
  521. class HttpError(Exception):
  522. def __init__(self, status_code, headers=None, body=None):
  523. self.status_code = status_code
  524. self.headers = headers
  525. self.body = body
  526. super(HttpError, self).__init__(status_code, headers, body)
  527. .. _task-custom-classes:
  528. Custom task classes
  529. ===================
  530. All tasks inherit from the :class:`@Task` class.
  531. The :meth:`~@Task.run` method becomes the task body.
  532. As an example, the following code,
  533. .. code-block:: python
  534. @app.task
  535. def add(x, y):
  536. return x + y
  537. will do roughly this behind the scenes:
  538. .. code-block:: python
  539. @app.task
  540. class AddTask(Task):
  541. def run(self, x, y):
  542. return x + y
  543. add = registry.tasks[AddTask.name]
  544. Instantiation
  545. -------------
  546. A task is **not** instantiated for every request, but is registered
  547. in the task registry as a global instance.
  548. This means that the ``__init__`` constructor will only be called
  549. once per process, and that the task class is semantically closer to an
  550. Actor.
  551. If you have a task,
  552. .. code-block:: python
  553. from celery import Task
  554. class NaiveAuthenticateServer(Task):
  555. def __init__(self):
  556. self.users = {'george': 'password'}
  557. def run(self, username, password):
  558. try:
  559. return self.users[username] == password
  560. except KeyError:
  561. return False
  562. And you route every request to the same process, then it
  563. will keep state between requests.
  564. This can also be useful to cache resources,
  565. e.g. a base Task class that caches a database connection:
  566. .. code-block:: python
  567. from celery import Task
  568. class DatabaseTask(Task):
  569. abstract = True
  570. _db = None
  571. @property
  572. def db(self):
  573. if self._db is None:
  574. self._db = Database.connect()
  575. return self._db
  576. that can be added to tasks like this:
  577. .. code-block:: python
  578. @app.task(base=DatabaseTask)
  579. def process_rows():
  580. for row in process_rows.db.table.all():
  581. ...
  582. The ``db`` attribute of the ``process_rows`` task will then
  583. always stay the same in each process.
  584. Abstract classes
  585. ----------------
  586. Abstract classes are not registered, but are used as the
  587. base class for new task types.
  588. .. code-block:: python
  589. from celery import Task
  590. class DebugTask(Task):
  591. abstract = True
  592. def after_return(self, *args, **kwargs):
  593. print('Task returned: {0!r}'.format(self.request)
  594. @app.task(base=DebugTask)
  595. def add(x, y):
  596. return x + y
  597. Handlers
  598. --------
  599. .. method:: after_return(self, status, retval, task_id, args, kwargs, einfo)
  600. Handler called after the task returns.
  601. :param status: Current task state.
  602. :param retval: Task return value/exception.
  603. :param task_id: Unique id of the task.
  604. :param args: Original arguments for the task that failed.
  605. :param kwargs: Original keyword arguments for the task
  606. that failed.
  607. :keyword einfo: :class:`~celery.datastructures.ExceptionInfo`
  608. instance, containing the traceback (if any).
  609. The return value of this handler is ignored.
  610. .. method:: on_failure(self, exc, task_id, args, kwargs, einfo)
  611. This is run by the worker when the task fails.
  612. :param exc: The exception raised by the task.
  613. :param task_id: Unique id of the failed task.
  614. :param args: Original arguments for the task that failed.
  615. :param kwargs: Original keyword arguments for the task
  616. that failed.
  617. :keyword einfo: :class:`~celery.datastructures.ExceptionInfo`
  618. instance, containing the traceback.
  619. The return value of this handler is ignored.
  620. .. method:: on_retry(self, exc, task_id, args, kwargs, einfo)
  621. This is run by the worker when the task is to be retried.
  622. :param exc: The exception sent to :meth:`~@Task.retry`.
  623. :param task_id: Unique id of the retried task.
  624. :param args: Original arguments for the retried task.
  625. :param kwargs: Original keyword arguments for the retried task.
  626. :keyword einfo: :class:`~celery.datastructures.ExceptionInfo`
  627. instance, containing the traceback.
  628. The return value of this handler is ignored.
  629. .. method:: on_success(self, retval, task_id, args, kwargs)
  630. Run by the worker if the task executes successfully.
  631. :param retval: The return value of the task.
  632. :param task_id: Unique id of the executed task.
  633. :param args: Original arguments for the executed task.
  634. :param kwargs: Original keyword arguments for the executed task.
  635. The return value of this handler is ignored.
  636. on_retry
  637. ~~~~~~~~
  638. .. _task-how-they-work:
  639. How it works
  640. ============
  641. Here comes the technical details, this part isn't something you need to know,
  642. but you may be interested.
  643. All defined tasks are listed in a registry. The registry contains
  644. a list of task names and their task classes. You can investigate this registry
  645. yourself:
  646. .. code-block:: python
  647. >>> from celery import current_app
  648. >>> current_app.tasks
  649. {'celery.chord_unlock':
  650. <@task: celery.chord_unlock>,
  651. 'celery.backend_cleanup':
  652. <@task: celery.backend_cleanup>,
  653. 'celery.chord':
  654. <@task: celery.chord>}
  655. This is the list of tasks built-in to celery. Note that tasks
  656. will only be registered when the module they are defined in is imported.
  657. The default loader imports any modules listed in the
  658. :setting:`CELERY_IMPORTS` setting.
  659. The entity responsible for registering your task in the registry is the
  660. metaclass: :class:`~celery.task.base.TaskType`.
  661. If you want to register your task manually you can mark the
  662. task as :attr:`~@Task.abstract`:
  663. .. code-block:: python
  664. class MyTask(Task):
  665. abstract = True
  666. This way the task won't be registered, but any task inheriting from
  667. it will be.
  668. When tasks are sent, no actual function code is sent with it, just the name
  669. of the task to execute. When the worker then receives the message it can look
  670. up the name in its task registry to find the execution code.
  671. This means that your workers should always be updated with the same software
  672. as the client. This is a drawback, but the alternative is a technical
  673. challenge that has yet to be solved.
  674. .. _task-best-practices:
  675. Tips and Best Practices
  676. =======================
  677. .. _task-ignore_results:
  678. Ignore results you don't want
  679. -----------------------------
  680. If you don't care about the results of a task, be sure to set the
  681. :attr:`~@Task.ignore_result` option, as storing results
  682. wastes time and resources.
  683. .. code-block:: python
  684. @app.task(ignore_result=True)
  685. def mytask(...)
  686. something()
  687. Results can even be disabled globally using the :setting:`CELERY_IGNORE_RESULT`
  688. setting.
  689. .. _task-disable-rate-limits:
  690. Disable rate limits if they're not used
  691. ---------------------------------------
  692. Disabling rate limits altogether is recommended if you don't have
  693. any tasks using them. This is because the rate limit subsystem introduces
  694. quite a lot of complexity.
  695. Set the :setting:`CELERY_DISABLE_RATE_LIMITS` setting to globally disable
  696. rate limits:
  697. .. code-block:: python
  698. CELERY_DISABLE_RATE_LIMITS = True
  699. You find additional optimization tips in the
  700. :ref:`Optimizing Guide <guide-optimizing>`.
  701. .. _task-synchronous-subtasks:
  702. Avoid launching synchronous subtasks
  703. ------------------------------------
  704. Having a task wait for the result of another task is really inefficient,
  705. and may even cause a deadlock if the worker pool is exhausted.
  706. Make your design asynchronous instead, for example by using *callbacks*.
  707. **Bad**:
  708. .. code-block:: python
  709. @app.task
  710. def update_page_info(url):
  711. page = fetch_page.delay(url).get()
  712. info = parse_page.delay(url, page).get()
  713. store_page_info.delay(url, info)
  714. @app.task
  715. def fetch_page(url):
  716. return myhttplib.get(url)
  717. @app.task
  718. def parse_page(url, page):
  719. return myparser.parse_document(page)
  720. @app.task
  721. def store_page_info(url, info):
  722. return PageInfo.objects.create(url, info)
  723. **Good**:
  724. .. code-block:: python
  725. def update_page_info(url):
  726. # fetch_page -> parse_page -> store_page
  727. chain = fetch_page.s() | parse_page.s() | store_page_info.s(url)
  728. chain()
  729. @app.task()
  730. def fetch_page(url):
  731. return myhttplib.get(url)
  732. @app.task()
  733. def parse_page(page):
  734. return myparser.parse_document(page)
  735. @app.task(ignore_result=True)
  736. def store_page_info(info, url):
  737. PageInfo.objects.create(url=url, info=info)
  738. Here I instead created a chain of tasks by linking together
  739. different :func:`~celery.subtask`'s.
  740. You can read about chains and other powerful constructs
  741. at :ref:`designing-workflows`.
  742. .. _task-performance-and-strategies:
  743. Performance and Strategies
  744. ==========================
  745. .. _task-granularity:
  746. Granularity
  747. -----------
  748. The task granularity is the amount of computation needed by each subtask.
  749. In general it is better to split the problem up into many small tasks, than
  750. have a few long running tasks.
  751. With smaller tasks you can process more tasks in parallel and the tasks
  752. won't run long enough to block the worker from processing other waiting tasks.
  753. However, executing a task does have overhead. A message needs to be sent, data
  754. may not be local, etc. So if the tasks are too fine-grained the additional
  755. overhead may not be worth it in the end.
  756. .. seealso::
  757. The book `Art of Concurrency`_ has a whole section dedicated to the topic
  758. of task granularity.
  759. .. _`Art of Concurrency`: http://oreilly.com/catalog/9780596521547
  760. .. _task-data-locality:
  761. Data locality
  762. -------------
  763. The worker processing the task should be as close to the data as
  764. possible. The best would be to have a copy in memory, the worst would be a
  765. full transfer from another continent.
  766. If the data is far away, you could try to run another worker at location, or
  767. if that's not possible - cache often used data, or preload data you know
  768. is going to be used.
  769. The easiest way to share data between workers is to use a distributed cache
  770. system, like `memcached`_.
  771. .. seealso::
  772. The paper `Distributed Computing Economics`_ by Jim Gray is an excellent
  773. introduction to the topic of data locality.
  774. .. _`Distributed Computing Economics`:
  775. http://research.microsoft.com/pubs/70001/tr-2003-24.pdf
  776. .. _`memcached`: http://memcached.org/
  777. .. _task-state:
  778. State
  779. -----
  780. Since celery is a distributed system, you can't know in which process, or
  781. on what machine the task will be executed. You can't even know if the task will
  782. run in a timely manner.
  783. The ancient async sayings tells us that “asserting the world is the
  784. responsibility of the task”. What this means is that the world view may
  785. have changed since the task was requested, so the task is responsible for
  786. making sure the world is how it should be; If you have a task
  787. that re-indexes a search engine, and the search engine should only be
  788. re-indexed at maximum every 5 minutes, then it must be the tasks
  789. responsibility to assert that, not the callers.
  790. Another gotcha is Django model objects. They shouldn't be passed on as
  791. arguments to tasks. It's almost always better to re-fetch the object from
  792. the database when the task is running instead, as using old data may lead
  793. to race conditions.
  794. Imagine the following scenario where you have an article and a task
  795. that automatically expands some abbreviations in it:
  796. .. code-block:: python
  797. class Article(models.Model):
  798. title = models.CharField()
  799. body = models.TextField()
  800. @app.task
  801. def expand_abbreviations(article):
  802. article.body.replace('MyCorp', 'My Corporation')
  803. article.save()
  804. First, an author creates an article and saves it, then the author
  805. clicks on a button that initiates the abbreviation task::
  806. >>> article = Article.objects.get(id=102)
  807. >>> expand_abbreviations.delay(model_object)
  808. Now, the queue is very busy, so the task won't be run for another 2 minutes.
  809. In the meantime another author makes changes to the article, so
  810. when the task is finally run, the body of the article is reverted to the old
  811. version because the task had the old body in its argument.
  812. Fixing the race condition is easy, just use the article id instead, and
  813. re-fetch the article in the task body:
  814. .. code-block:: python
  815. @app.task
  816. def expand_abbreviations(article_id):
  817. article = Article.objects.get(id=article_id)
  818. article.body.replace('MyCorp', 'My Corporation')
  819. article.save()
  820. >>> expand_abbreviations(article_id)
  821. There might even be performance benefits to this approach, as sending large
  822. messages may be expensive.
  823. .. _task-database-transactions:
  824. Database transactions
  825. ---------------------
  826. Let's have a look at another example:
  827. .. code-block:: python
  828. from django.db import transaction
  829. @transaction.commit_on_success
  830. def create_article(request):
  831. article = Article.objects.create(....)
  832. expand_abbreviations.delay(article.pk)
  833. This is a Django view creating an article object in the database,
  834. then passing the primary key to a task. It uses the `commit_on_success`
  835. decorator, which will commit the transaction when the view returns, or
  836. roll back if the view raises an exception.
  837. There is a race condition if the task starts executing
  838. before the transaction has been committed; The database object does not exist
  839. yet!
  840. The solution is to *always commit transactions before sending tasks
  841. depending on state from the current transaction*:
  842. .. code-block:: python
  843. @transaction.commit_manually
  844. def create_article(request):
  845. try:
  846. article = Article.objects.create(...)
  847. except:
  848. transaction.rollback()
  849. raise
  850. else:
  851. transaction.commit()
  852. expand_abbreviations.delay(article.pk)
  853. .. _task-example:
  854. Example
  855. =======
  856. Let's take a real wold example; A blog where comments posted needs to be
  857. filtered for spam. When the comment is created, the spam filter runs in the
  858. background, so the user doesn't have to wait for it to finish.
  859. I have a Django blog application allowing comments
  860. on blog posts. I'll describe parts of the models/views and tasks for this
  861. application.
  862. blog/models.py
  863. --------------
  864. The comment model looks like this:
  865. .. code-block:: python
  866. from django.db import models
  867. from django.utils.translation import ugettext_lazy as _
  868. class Comment(models.Model):
  869. name = models.CharField(_('name'), max_length=64)
  870. email_address = models.EmailField(_('email address'))
  871. homepage = models.URLField(_('home page'),
  872. blank=True, verify_exists=False)
  873. comment = models.TextField(_('comment'))
  874. pub_date = models.DateTimeField(_('Published date'),
  875. editable=False, auto_add_now=True)
  876. is_spam = models.BooleanField(_('spam?'),
  877. default=False, editable=False)
  878. class Meta:
  879. verbose_name = _('comment')
  880. verbose_name_plural = _('comments')
  881. In the view where the comment is posted, I first write the comment
  882. to the database, then I launch the spam filter task in the background.
  883. .. _task-example-blog-views:
  884. blog/views.py
  885. -------------
  886. .. code-block:: python
  887. from django import forms
  888. from django.http import HttpResponseRedirect
  889. from django.template.context import RequestContext
  890. from django.shortcuts import get_object_or_404, render_to_response
  891. from blog import tasks
  892. from blog.models import Comment
  893. class CommentForm(forms.ModelForm):
  894. class Meta:
  895. model = Comment
  896. def add_comment(request, slug, template_name='comments/create.html'):
  897. post = get_object_or_404(Entry, slug=slug)
  898. remote_addr = request.META.get('REMOTE_ADDR')
  899. if request.method == 'post':
  900. form = CommentForm(request.POST, request.FILES)
  901. if form.is_valid():
  902. comment = form.save()
  903. # Check spam asynchronously.
  904. tasks.spam_filter.delay(comment_id=comment.id,
  905. remote_addr=remote_addr)
  906. return HttpResponseRedirect(post.get_absolute_url())
  907. else:
  908. form = CommentForm()
  909. context = RequestContext(request, {'form': form})
  910. return render_to_response(template_name, context_instance=context)
  911. To filter spam in comments I use `Akismet`_, the service
  912. used to filter spam in comments posted to the free weblog platform
  913. `Wordpress`. `Akismet`_ is free for personal use, but for commercial use you
  914. need to pay. You have to sign up to their service to get an API key.
  915. To make API calls to `Akismet`_ I use the `akismet.py`_ library written by
  916. `Michael Foord`_.
  917. .. _task-example-blog-tasks:
  918. blog/tasks.py
  919. -------------
  920. .. code-block:: python
  921. from celery import Celery
  922. from akismet import Akismet
  923. from django.core.exceptions import ImproperlyConfigured
  924. from django.contrib.sites.models import Site
  925. from blog.models import Comment
  926. app = Celery(broker='amqp://')
  927. @app.task
  928. def spam_filter(comment_id, remote_addr=None):
  929. logger = spam_filter.get_logger()
  930. logger.info('Running spam filter for comment %s', comment_id)
  931. comment = Comment.objects.get(pk=comment_id)
  932. current_domain = Site.objects.get_current().domain
  933. akismet = Akismet(settings.AKISMET_KEY, 'http://{0}'.format(domain))
  934. if not akismet.verify_key():
  935. raise ImproperlyConfigured('Invalid AKISMET_KEY')
  936. is_spam = akismet.comment_check(user_ip=remote_addr,
  937. comment_content=comment.comment,
  938. comment_author=comment.name,
  939. comment_author_email=comment.email_address)
  940. if is_spam:
  941. comment.is_spam = True
  942. comment.save()
  943. return is_spam
  944. .. _`Akismet`: http://akismet.com/faq/
  945. .. _`akismet.py`: http://www.voidspace.org.uk/downloads/akismet.py
  946. .. _`Michael Foord`: http://www.voidspace.org.uk/