tasks.rst 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062
  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 the worker can find the right function to execute.
  11. A task message is not removed from the queue
  12. until that message has been :term:`acknowledged` by a worker. A worker can reserve
  13. many messages in advance and even if the worker is killed -- by power failure
  14. or some other reason -- the message will be redelivered to another worker.
  15. Ideally task functions should be :term:`idempotent`: meaning
  16. the function won't cause unintended 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, just before it's executed,
  20. so that a task invocation that already started is never executed again.
  21. If your task is idempotent you can set the :attr:`~Task.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. Note that the worker will acknowledge the message if the child process executing
  25. the task is terminated (either by the task calling :func:`sys.exit`, or by signal)
  26. even when :attr:`~Task.acks_late` is enabled. This behavior is by purpose
  27. as...
  28. #. We don't want to rerun tasks that forces the kernel to send
  29. a :sig:`SIGSEGV` (segmentation fault) or similar signals to the process.
  30. #. We assume that a system administrator deliberately killing the task
  31. does not want it to automatically restart.
  32. #. A task that allocates too much memory is in danger of triggering the kernel
  33. OOM killer, the same may happen again.
  34. #. A task that always fails when redelivered may cause a high-frequency
  35. message loop taking down the system.
  36. If you really want a task to be redelivered in these scenarios you should
  37. consider enabling the :setting:`task_reject_on_worker_lost` setting.
  38. .. warning::
  39. A task that blocks indefinitely may eventually stop the worker instance
  40. from doing any other work.
  41. If you task does I/O then make sure you add timeouts to these operations,
  42. like adding a timeout to a web request using the :pypi:`requests` library:
  43. .. code-block:: python
  44. connect_timeout, read_timeout = 5.0, 30.0
  45. response = requests.get(URL, timeout=(connect_timeout, read_timeout))
  46. :ref:`Time limits <worker-time-limits>` are convenient for making sure all
  47. tasks return in a timely manner, but a time limit event will actually kill
  48. the process by force so only use them to detect cases where you haven't
  49. used manual timeouts yet.
  50. The default prefork pool scheduler is not friendly to long-running tasks,
  51. so if you have tasks that run for minutes/hours make sure you enable
  52. the :option:`-Ofair <celery worker -O>` command-line argument to
  53. the :program:`celery worker`. See :ref:`prefork-pool-prefetch` for more
  54. information, and for the best performance route long-running and
  55. short-running tasks to dedicated workers (:ref:`routing-automatic`).
  56. If your worker hangs then please investigate what tasks are running
  57. before submitting an issue, as most likely the hanging is caused
  58. by one or more tasks hanging on a network operation.
  59. --
  60. In this chapter you'll learn all about defining tasks,
  61. and this is the **table of contents**:
  62. .. contents::
  63. :local:
  64. :depth: 1
  65. .. _task-basics:
  66. Basics
  67. ======
  68. You can easily create a task from any callable by using
  69. the :meth:`~@task` decorator:
  70. .. code-block:: python
  71. from .models import User
  72. @app.task
  73. def create_user(username, password):
  74. User.objects.create(username=username, password=password)
  75. There are also many :ref:`options <task-options>` that can be set for the task,
  76. these can be specified as arguments to the decorator:
  77. .. code-block:: python
  78. @app.task(serializer='json')
  79. def create_user(username, password):
  80. User.objects.create(username=username, password=password)
  81. .. sidebar:: How do I import the task decorator? And what's "app"?
  82. The task decorator is available on your :class:`@Celery` application instance,
  83. if you don't know what this is then please read :ref:`first-steps`.
  84. If you're using Django (see :ref:`django-first-steps`), or you're the author
  85. of a library then you probably want to use the :func:`@shared_task` decorator:
  86. .. code-block:: python
  87. from celery import shared_task
  88. @shared_task
  89. def add(x, y):
  90. return x + y
  91. .. sidebar:: Multiple decorators
  92. When using multiple decorators in combination with the task
  93. decorator you must make sure that the `task`
  94. decorator is applied last (oddly, in Python this means it must
  95. be first in the list):
  96. .. code-block:: python
  97. @app.task
  98. @decorator2
  99. @decorator1
  100. def add(x, y):
  101. return x + y
  102. Bound tasks
  103. -----------
  104. A task being bound means the first argument to the task will always
  105. be the task instance (``self``), just like Python bound methods:
  106. .. code-block:: python
  107. logger = get_task_logger(__name__)
  108. @task(bind=True)
  109. def add(self, x, y):
  110. logger.info(self.request.id)
  111. Bound tasks are needed for retries (using :meth:`Task.retry() <@Task.retry>`),
  112. for accessing information about the current task request, and for any
  113. additional functionality you add to custom task base classes.
  114. Task inheritance
  115. ----------------
  116. The ``base`` argument to the task decorator specifies the base class of the task:
  117. .. code-block:: python
  118. import celery
  119. class MyTask(celery.Task):
  120. def on_failure(self, exc, task_id, args, kwargs, einfo):
  121. print('{0!r} failed: {1!r}'.format(task_id, exc))
  122. @task(base=MyTask)
  123. def add(x, y):
  124. raise KeyError()
  125. .. _task-names:
  126. Names
  127. =====
  128. Every task must have a unique name.
  129. If no explicit name is provided the task decorator will generate one for you,
  130. and this name will be based on 1) the module the task is defined in, and 2)
  131. the name of the task function.
  132. Example setting explicit name:
  133. .. code-block:: pycon
  134. >>> @app.task(name='sum-of-two-numbers')
  135. >>> def add(x, y):
  136. ... return x + y
  137. >>> add.name
  138. 'sum-of-two-numbers'
  139. A best practice is to use the module name as a name-space,
  140. this way names won't collide if there's already a task with that name
  141. defined in another module.
  142. .. code-block:: pycon
  143. >>> @app.task(name='tasks.add')
  144. >>> def add(x, y):
  145. ... return x + y
  146. You can tell the name of the task by investigating its ``.name`` attribute:
  147. .. code-block:: pycon
  148. >>> add.name
  149. 'tasks.add'
  150. The name we specified here (``tasks.add``) is exactly the name that would've
  151. been automatically generated for us if the task was defined in a module
  152. named :file:`tasks.py`:
  153. :file:`tasks.py`:
  154. .. code-block:: python
  155. @app.task
  156. def add(x, y):
  157. return x + y
  158. .. code-block:: pycon
  159. >>> from tasks import add
  160. >>> add.name
  161. 'tasks.add'
  162. .. _task-naming-relative-imports:
  163. Automatic naming and relative imports
  164. -------------------------------------
  165. .. sidebar:: Absolute Imports
  166. The best practice for developers targeting Python 2 is to add the
  167. following to the top of **every module**:
  168. .. code-block:: python
  169. from __future__ import absolute_import
  170. This will force you to always use absolute imports so you will
  171. never have any problems with tasks using relative names.
  172. Absolute imports are the default in Python 3 so you don't need this
  173. if you target that version.
  174. Relative imports and automatic name generation don't go well together,
  175. so if you're using relative imports you should set the name explicitly.
  176. For example if the client imports the module ``"myapp.tasks"``
  177. as ``".tasks"``, and the worker imports the module as ``"myapp.tasks"``,
  178. the generated names won't match and an :exc:`~@NotRegistered` error will
  179. be raised by the worker.
  180. This is also the case when using Django and using ``project.myapp``-style
  181. naming in ``INSTALLED_APPS``:
  182. .. code-block:: python
  183. INSTALLED_APPS = ['project.myapp']
  184. If you install the app under the name ``project.myapp`` then the
  185. tasks module will be imported as ``project.myapp.tasks``,
  186. so you must make sure you always import the tasks using the same name:
  187. .. code-block:: pycon
  188. >>> from project.myapp.tasks import mytask # << GOOD
  189. >>> from myapp.tasks import mytask # << BAD!!!
  190. The second example will cause the task to be named differently
  191. since the worker and the client imports the modules under different names:
  192. .. code-block:: pycon
  193. >>> from project.myapp.tasks import mytask
  194. >>> mytask.name
  195. 'project.myapp.tasks.mytask'
  196. >>> from myapp.tasks import mytask
  197. >>> mytask.name
  198. 'myapp.tasks.mytask'
  199. For this reason you must be consistent in how you
  200. import modules, and that is also a Python best practice.
  201. Similarly, you shouldn't use old-style relative imports:
  202. .. code-block:: python
  203. from module import foo # BAD!
  204. from proj.module import foo # GOOD!
  205. New-style relative imports are fine and can be used:
  206. .. code-block:: python
  207. from .module import foo # GOOD!
  208. If you want to use Celery with a project already using these patterns
  209. extensively and you don't have the time to refactor the existing code
  210. then you can consider specifying the names explicitly instead of relying
  211. on the automatic naming:
  212. .. code-block:: python
  213. @task(name='proj.tasks.add')
  214. def add(x, y):
  215. return x + y
  216. .. _task-name-generator-info:
  217. Changing the automatic naming behavior
  218. --------------------------------------
  219. .. versionadded:: 4.0
  220. There are some cases when the default automatic naming isn't suitable.
  221. Consider having many tasks within many different modules::
  222. project/
  223. /__init__.py
  224. /celery.py
  225. /moduleA/
  226. /__init__.py
  227. /tasks.py
  228. /moduleB/
  229. /__init__.py
  230. /tasks.py
  231. Using the default automatic naming, each task will have a generated name
  232. like `moduleA.tasks.taskA`, `moduleA.tasks.taskB`, `moduleB.tasks.test`,
  233. and so on. You may want to get rid of having `tasks` in all task names.
  234. As pointed above, you can explicitly give names for all tasks, or you
  235. can change the automatic naming behavior by overriding
  236. :meth:`@gen_task_name`. Continuing with the example, `celery.py`
  237. may contain:
  238. .. code-block:: python
  239. from celery import Celery
  240. class MyCelery(Celery):
  241. def gen_task_name(self, name, module):
  242. if module.endswith('.tasks'):
  243. module = module[:-6]
  244. return super(MyCelery, self).gen_task_name(name, module)
  245. app = MyCelery('main')
  246. So each task will have a name like `moduleA.taskA`, `moduleA.taskB` and
  247. `moduleB.test`.
  248. .. warning::
  249. Make sure that your :meth:`@gen_task_name` is a pure function: meaning
  250. that for the same input it must always return the same output.
  251. .. _task-request-info:
  252. Task Request
  253. ============
  254. :attr:`Task.request <@Task.request>` contains information and state
  255. related to the currently executing task.
  256. The request defines the following attributes:
  257. :id: The unique id of the executing task.
  258. :group: The unique id of the task's :ref:`group <canvas-group>`, if this task is a member.
  259. :chord: The unique id of the chord this task belongs to (if the task
  260. is part of the header).
  261. :correlation_id: Custom ID used for things like de-duplication.
  262. :args: Positional arguments.
  263. :kwargs: Keyword arguments.
  264. :origin: Name of host that sent this task.
  265. :retries: How many times the current task has been retried.
  266. An integer starting at `0`.
  267. :is_eager: Set to :const:`True` if the task is executed locally in
  268. the client, not by a worker.
  269. :eta: The original ETA of the task (if any).
  270. This is in UTC time (depending on the :setting:`enable_utc`
  271. setting).
  272. :expires: The original expiry time of the task (if any).
  273. This is in UTC time (depending on the :setting:`enable_utc`
  274. setting).
  275. :hostname: Node name of the worker instance executing the task.
  276. :delivery_info: Additional message delivery information. This is a mapping
  277. containing the exchange and routing key used to deliver this
  278. task. Used by for example :meth:`Task.retry() <@Task.retry>`
  279. to resend the task to the same destination queue.
  280. Availability of keys in this dict depends on the
  281. message broker used.
  282. :reply-to: Name of queue to send replies back to (used with RPC result
  283. backend for example).
  284. :called_directly: This flag is set to true if the task wasn't
  285. executed by the worker.
  286. :timelimit: A tuple of the current ``(soft, hard)`` time limits active for
  287. this task (if any).
  288. :callbacks: A list of signatures to be called if this task returns successfully.
  289. :errback: A list of signatures to be called if this task fails.
  290. :utc: Set to true the caller has UTC enabled (:setting:`enable_utc`).
  291. .. versionadded:: 3.1
  292. :headers: Mapping of message headers sent with this task message
  293. (may be :const:`None`).
  294. :reply_to: Where to send reply to (queue name).
  295. :correlation_id: Usually the same as the task id, often used in amqp
  296. to keep track of what a reply is for.
  297. .. versionadded:: 4.0
  298. :root_id: The unique id of the first task in the workflow this task
  299. is part of (if any).
  300. :parent_id: The unique id of the task that called this task (if any).
  301. :chain: Reversed list of tasks that form a chain (if any).
  302. The last item in this list will be the next task to succeed the
  303. current task. If using version one of the task protocol the chain
  304. tasks will be in ``request.callbacks`` instead.
  305. Example
  306. -------
  307. An example task accessing information in the context is:
  308. .. code-block:: python
  309. @app.task(bind=True)
  310. def dump_context(self, x, y):
  311. print('Executing task id {0.id}, args: {0.args!r} kwargs: {0.kwargs!r}'.format(
  312. self.request))
  313. The ``bind`` argument means that the function will be a "bound method" so
  314. that you can access attributes and methods on the task type instance.
  315. .. _task-logging:
  316. Logging
  317. =======
  318. The worker will automatically set up logging for you, or you can
  319. configure logging manually.
  320. A special logger is available named "celery.task", you can inherit
  321. from this logger to automatically get the task name and unique id as part
  322. of the logs.
  323. The best practice is to create a common logger
  324. for all of your tasks at the top of your module:
  325. .. code-block:: python
  326. from celery.utils.log import get_task_logger
  327. logger = get_task_logger(__name__)
  328. @app.task
  329. def add(x, y):
  330. logger.info('Adding {0} + {1}'.format(x, y))
  331. return x + y
  332. Celery uses the standard Python logger library,
  333. and the documentation can be found :mod:`here <logging>`.
  334. You can also use :func:`print`, as anything written to standard
  335. out/-err will be redirected to the logging system (you can disable this,
  336. see :setting:`worker_redirect_stdouts`).
  337. .. note::
  338. The worker won't update the redirection if you create a logger instance
  339. somewhere in your task or task module.
  340. If you want to redirect ``sys.stdout`` and ``sys.stderr`` to a custom
  341. logger you have to enable this manually, for example:
  342. .. code-block:: python
  343. import sys
  344. logger = get_task_logger(__name__)
  345. @app.task(bind=True)
  346. def add(self, x, y):
  347. old_outs = sys.stdout, sys.stderr
  348. rlevel = self.app.conf.worker_redirect_stdouts_level
  349. try:
  350. self.app.log.redirect_stdouts_to_logger(logger, rlevel)
  351. print('Adding {0} + {1}'.format(x, y))
  352. return x + y
  353. finally:
  354. sys.stdout, sys.stderr = old_outs
  355. .. _task-argument-checking:
  356. Argument checking
  357. -----------------
  358. .. versionadded:: 4.0
  359. Celery will verify the arguments passed when you call the task, just
  360. like Python does when calling a normal function:
  361. .. code-block:: pycon
  362. >>> @app.task
  363. ... def add(x, y):
  364. ... return x + y
  365. # Calling the task with two arguments works:
  366. >>> add.delay(8, 8)
  367. <AsyncResult: f59d71ca-1549-43e0-be41-4e8821a83c0c>
  368. # Calling the task with only one argument fails:
  369. >>> add.delay(8)
  370. Traceback (most recent call last):
  371. File "<stdin>", line 1, in <module>
  372. File "celery/app/task.py", line 376, in delay
  373. return self.apply_async(args, kwargs)
  374. File "celery/app/task.py", line 485, in apply_async
  375. check_arguments(*(args or ()), **(kwargs or {}))
  376. TypeError: add() takes exactly 2 arguments (1 given)
  377. You can disable the argument checking for any task by setting its
  378. :attr:`~@Task.typing` attribute to :const:`False`:
  379. .. code-block:: pycon
  380. >>> @app.task(typing=False)
  381. ... def add(x, y):
  382. ... return x + y
  383. # Works locally, but the worker reciving the task will raise an error.
  384. >>> add.delay(8)
  385. <AsyncResult: f59d71ca-1549-43e0-be41-4e8821a83c0c>
  386. .. _task-hiding-sensitive-information:
  387. Hiding sensitive information in arguments
  388. -----------------------------------------
  389. .. versionadded:: 4.0
  390. When using :setting:`task_protocol` 2 or higher (default since 4.0), you can
  391. override how positional arguments and keyword arguments are represented in logs
  392. and monitoring events using the ``argsrepr`` and ``kwargsrepr`` calling
  393. arguments:
  394. .. code-block:: pycon
  395. >>> add.apply_async((2, 3), argsrepr='(<secret-x>, <secret-y>)')
  396. >>> charge.s(account, card='1234 5678 1234 5678').set(
  397. ... kwargsrepr=repr({'card': '**** **** **** 5678'})
  398. ... ).delay()
  399. .. warning::
  400. Sensitive information will still be accessible to anyone able
  401. to read your task message from the broker, or otherwise able intercept it.
  402. For this reason you should probably encrypt your message if it contains
  403. sensitive information, or in this example with a credit card number
  404. the actual number could be stored encrypted in a secure store that you retrieve
  405. and decrypt in the task itself.
  406. .. _task-retry:
  407. Retrying
  408. ========
  409. :meth:`Task.retry() <@Task.retry>` can be used to re-execute the task,
  410. for example in the event of recoverable errors.
  411. When you call ``retry`` it'll send a new message, using the same
  412. task-id, and it'll take care to make sure the message is delivered
  413. to the same queue as the originating task.
  414. When a task is retried this is also recorded as a task state,
  415. so that you can track the progress of the task using the result
  416. instance (see :ref:`task-states`).
  417. Here's an example using ``retry``:
  418. .. code-block:: python
  419. @app.task(bind=True)
  420. def send_twitter_status(self, oauth, tweet):
  421. try:
  422. twitter = Twitter(oauth)
  423. twitter.update_status(tweet)
  424. except (Twitter.FailWhaleError, Twitter.LoginError) as exc:
  425. raise self.retry(exc=exc)
  426. .. note::
  427. The :meth:`Task.retry() <@Task.retry>` call will raise an exception so any
  428. code after the retry won't be reached. This is the :exc:`~@Retry`
  429. exception, it isn't handled as an error but rather as a semi-predicate
  430. to signify to the worker that the task is to be retried,
  431. so that it can store the correct state when a result backend is enabled.
  432. This is normal operation and always happens unless the
  433. ``throw`` argument to retry is set to :const:`False`.
  434. The bind argument to the task decorator will give access to ``self`` (the
  435. task type instance).
  436. The ``exc`` method is used to pass exception information that's
  437. used in logs, and when storing task results.
  438. Both the exception and the traceback will
  439. be available in the task state (if a result backend is enabled).
  440. If the task has a ``max_retries`` value the current exception
  441. will be re-raised if the max number of retries has been exceeded,
  442. but this won't happen if:
  443. - An ``exc`` argument wasn't given.
  444. In this case the :exc:`~@MaxRetriesExceededError`
  445. exception will be raised.
  446. - There's no current exception
  447. If there's no original exception to re-raise the ``exc``
  448. argument will be used instead, so:
  449. .. code-block:: python
  450. self.retry(exc=Twitter.LoginError())
  451. will raise the ``exc`` argument given.
  452. .. _task-retry-custom-delay:
  453. Using a custom retry delay
  454. --------------------------
  455. When a task is to be retried, it can wait for a given amount of time
  456. before doing so, and the default delay is defined by the
  457. :attr:`~@Task.default_retry_delay`
  458. attribute. By default this is set to 3 minutes. Note that the
  459. unit for setting the delay is in seconds (int or float).
  460. You can also provide the `countdown` argument to :meth:`~@Task.retry` to
  461. override this default.
  462. .. code-block:: python
  463. @app.task(bind=True, default_retry_delay=30 * 60) # retry in 30 minutes.
  464. def add(self, x, y):
  465. try:
  466. something_raising()
  467. except Exception as exc:
  468. # overrides the default delay to retry after 1 minute
  469. raise self.retry(exc=exc, countdown=60)
  470. .. _task-autoretry:
  471. Automatic retry for known exceptions
  472. ------------------------------------
  473. .. versionadded:: 4.0
  474. Sometimes you just want to retry a task whenever a particular exception
  475. is raised.
  476. Fortunately, you can tell Celery to automatically retry a task using
  477. `autoretry_for` argument in the :meth:`~@Celery.task` decorator:
  478. .. code-block:: python
  479. from twitter.exceptions import FailWhaleError
  480. @app.task(autoretry_for=(FailWhaleError,))
  481. def refresh_timeline(user):
  482. return twitter.refresh_timeline(user)
  483. If you want to specify custom arguments for an internal :meth:`~@Task.retry`
  484. call, pass `retry_kwargs` argument to :meth:`~@Celery.task` decorator:
  485. .. code-block:: python
  486. @app.task(autoretry_for=(FailWhaleError,),
  487. retry_kwargs={'max_retries': 5})
  488. def refresh_timeline(user):
  489. return twitter.refresh_timeline(user)
  490. This is provided as an alternative to manually handling the exceptions,
  491. and the example above will do the same as wrapping the task body
  492. in a :keyword:`try` ... :keyword:`except` statement:
  493. .. code-block:: python
  494. @app.task
  495. def refresh_timeline(user):
  496. try:
  497. twitter.refresh_timeline(user)
  498. except FailWhaleError as exc:
  499. raise div.retry(exc=exc, max_retries=5)
  500. If you want to automatically retry on any error, simply use:
  501. .. code-block:: python
  502. @app.task(autoretry_for=(Exception,))
  503. def x():
  504. ...
  505. .. versionadded:: 4.2
  506. If your tasks depend on another service, like making a request to an API,
  507. then it's a good idea to use `exponential backoff`_ to avoid overwhelming the
  508. service with your requests. Fortunately, Celery's automatic retry support
  509. makes it easy. Just specify the :attr:`~Task.retry_backoff` argument, like this:
  510. .. code-block:: python
  511. from requests.exceptions import RequestException
  512. @app.task(autoretry_for=(RequestException,), retry_backoff=True)
  513. def x():
  514. ...
  515. By default, this exponential backoff will also introduce random jitter_ to
  516. avoid having all the tasks run at the same moment. It will also cap the
  517. maximum backoff delay to 10 minutes. All these settings can be customized
  518. via options documented below.
  519. .. attribute:: Task.autoretry_for
  520. A list/tuple of exception classes. If any of these exceptions are raised
  521. during the execution of the task, the task will automatically be retried.
  522. By default, no exceptions will be autoretried.
  523. .. attribute:: Task.retry_kwargs
  524. A dictionary. Use this to customize how autoretries are executed.
  525. Note that if you use the exponential backoff options below, the `countdown`
  526. task option will be determined by Celery's autoretry system, and any
  527. `countdown` included in this dictionary will be ignored.
  528. .. attribute:: Task.retry_backoff
  529. A boolean, or a number. If this option is set to ``True``, autoretries
  530. will be delayed following the rules of `exponential backoff`_. The first
  531. retry will have a delay of 1 second, the second retry will have a delay
  532. of 2 seconds, the third will delay 4 seconds, the fourth will delay 8
  533. seconds, and so on. (However, this delay value is modified by
  534. :attr:`~Task.retry_jitter`, if it is enabled.)
  535. If this option is set to a number, it is used as a
  536. delay factor. For example, if this option is set to ``3``, the first retry
  537. will delay 3 seconds, the second will delay 6 seconds, the third will
  538. delay 12 seconds, the fourth will delay 24 seconds, and so on. By default,
  539. this option is set to ``False``, and autoretries will not be delayed.
  540. .. attribute:: Task.retry_backoff_max
  541. A number. If ``retry_backoff`` is enabled, this option will set a maximum
  542. delay in seconds between task autoretries. By default, this option is set to ``600``,
  543. which is 10 minutes.
  544. .. attribute:: Task.retry_jitter
  545. A boolean. `Jitter`_ is used to introduce randomness into
  546. exponential backoff delays, to prevent all tasks in the queue from being
  547. executed simultaneously. If this option is set to ``True``, the delay
  548. value calculated by :attr:`~Task.retry_backoff` is treated as a maximum,
  549. and the actual delay value will be a random number between zero and that
  550. maximum. By default, this option is set to ``True``.
  551. .. _task-options:
  552. List of Options
  553. ===============
  554. The task decorator can take a number of options that change the way
  555. the task behaves, for example you can set the rate limit for a task
  556. using the :attr:`rate_limit` option.
  557. Any keyword argument passed to the task decorator will actually be set
  558. as an attribute of the resulting task class, and this is a list
  559. of the built-in attributes.
  560. General
  561. -------
  562. .. _task-general-options:
  563. .. attribute:: Task.name
  564. The name the task is registered as.
  565. You can set this name manually, or a name will be
  566. automatically generated using the module and class name.
  567. See also :ref:`task-names`.
  568. .. attribute:: Task.request
  569. If the task is being executed this will contain information
  570. about the current request. Thread local storage is used.
  571. See :ref:`task-request-info`.
  572. .. attribute:: Task.max_retries
  573. Only applies if the task calls ``self.retry`` or if the task is decorated
  574. with the :ref:`autoretry_for <task-autoretry>` argument.
  575. The maximum number of attempted retries before giving up.
  576. If the number of retries exceeds this value a :exc:`~@MaxRetriesExceededError`
  577. exception will be raised.
  578. .. note::
  579. You have to call :meth:`~@Task.retry`
  580. manually, as it won't automatically retry on exception..
  581. The default is ``3``.
  582. A value of :const:`None` will disable the retry limit and the
  583. task will retry forever until it succeeds.
  584. .. attribute:: Task.throws
  585. Optional tuple of expected error classes that shouldn't be regarded
  586. as an actual error.
  587. Errors in this list will be reported as a failure to the result backend,
  588. but the worker won't log the event as an error, and no traceback will
  589. be included.
  590. Example:
  591. .. code-block:: python
  592. @task(throws=(KeyError, HttpNotFound)):
  593. def get_foo():
  594. something()
  595. Error types:
  596. - Expected errors (in ``Task.throws``)
  597. Logged with severity ``INFO``, traceback excluded.
  598. - Unexpected errors
  599. Logged with severity ``ERROR``, with traceback included.
  600. .. attribute:: Task.default_retry_delay
  601. Default time in seconds before a retry of the task
  602. should be executed. Can be either :class:`int` or :class:`float`.
  603. Default is a three minute delay.
  604. .. attribute:: Task.rate_limit
  605. Set the rate limit for this task type (limits the number of tasks
  606. that can be run in a given time frame). Tasks will still complete when
  607. a rate limit is in effect, but it may take some time before it's allowed to
  608. start.
  609. If this is :const:`None` no rate limit is in effect.
  610. If it is an integer or float, it is interpreted as "tasks per second".
  611. The rate limits can be specified in seconds, minutes or hours
  612. by appending `"/s"`, `"/m"` or `"/h"` to the value. Tasks will be evenly
  613. distributed over the specified time frame.
  614. Example: `"100/m"` (hundred tasks a minute). This will enforce a minimum
  615. delay of 600ms between starting two tasks on the same worker instance.
  616. Default is the :setting:`task_default_rate_limit` setting:
  617. if not specified means rate limiting for tasks is disabled by default.
  618. Note that this is a *per worker instance* rate limit, and not a global
  619. rate limit. To enforce a global rate limit (e.g., for an API with a
  620. maximum number of requests per second), you must restrict to a given
  621. queue.
  622. .. attribute:: Task.time_limit
  623. The hard time limit, in seconds, for this task.
  624. When not set the workers default is used.
  625. .. attribute:: Task.soft_time_limit
  626. The soft time limit for this task.
  627. When not set the workers default is used.
  628. .. attribute:: Task.ignore_result
  629. Don't store task state. Note that this means you can't use
  630. :class:`~celery.result.AsyncResult` to check if the task is ready,
  631. or get its return value.
  632. .. attribute:: Task.store_errors_even_if_ignored
  633. If :const:`True`, errors will be stored even if the task is configured
  634. to ignore results.
  635. .. attribute:: Task.serializer
  636. A string identifying the default serialization
  637. method to use. Defaults to the :setting:`task_serializer`
  638. setting. Can be `pickle`, `json`, `yaml`, or any custom
  639. serialization methods that have been registered with
  640. :mod:`kombu.serialization.registry`.
  641. Please see :ref:`calling-serializers` for more information.
  642. .. attribute:: Task.compression
  643. A string identifying the default compression scheme to use.
  644. Defaults to the :setting:`task_compression` setting.
  645. Can be `gzip`, or `bzip2`, or any custom compression schemes
  646. that have been registered with the :mod:`kombu.compression` registry.
  647. Please see :ref:`calling-compression` for more information.
  648. .. attribute:: Task.backend
  649. The result store backend to use for this task. An instance of one of the
  650. backend classes in `celery.backends`. Defaults to `app.backend`,
  651. defined by the :setting:`result_backend` setting.
  652. .. attribute:: Task.acks_late
  653. If set to :const:`True` messages for this task will be acknowledged
  654. **after** the task has been executed, not *just before* (the default
  655. behavior).
  656. Note: This means the task may be executed multiple times should the worker
  657. crash in the middle of execution. Make sure your tasks are
  658. :term:`idempotent`.
  659. The global default can be overridden by the :setting:`task_acks_late`
  660. setting.
  661. .. _task-track-started:
  662. .. attribute:: Task.track_started
  663. If :const:`True` the task will report its status as "started"
  664. when the task is executed by a worker.
  665. The default value is :const:`False` as the normal behavior is to not
  666. report that level of granularity. Tasks are either pending, finished,
  667. or waiting to be retried. Having a "started" status can be useful for
  668. when there are long running tasks and there's a need to report what
  669. task is currently running.
  670. The host name and process id of the worker executing the task
  671. will be available in the state meta-data (e.g., `result.info['pid']`)
  672. The global default can be overridden by the
  673. :setting:`task_track_started` setting.
  674. .. seealso::
  675. The API reference for :class:`~@Task`.
  676. .. _task-states:
  677. States
  678. ======
  679. Celery can keep track of the tasks current state. The state also contains the
  680. result of a successful task, or the exception and traceback information of a
  681. failed task.
  682. There are several *result backends* to choose from, and they all have
  683. different strengths and weaknesses (see :ref:`task-result-backends`).
  684. During its lifetime a task will transition through several possible states,
  685. and each state may have arbitrary meta-data attached to it. When a task
  686. moves into a new state the previous state is
  687. forgotten about, but some transitions can be deduced, (e.g., a task now
  688. in the :state:`FAILED` state, is implied to have been in the
  689. :state:`STARTED` state at some point).
  690. There are also sets of states, like the set of
  691. :state:`FAILURE_STATES`, and the set of :state:`READY_STATES`.
  692. The client uses the membership of these sets to decide whether
  693. the exception should be re-raised (:state:`PROPAGATE_STATES`), or whether
  694. the state can be cached (it can if the task is ready).
  695. You can also define :ref:`custom-states`.
  696. .. _task-result-backends:
  697. Result Backends
  698. ---------------
  699. If you want to keep track of tasks or need the return values, then Celery
  700. must store or send the states somewhere so that they can be retrieved later.
  701. There are several built-in result backends to choose from: SQLAlchemy/Django ORM,
  702. Memcached, RabbitMQ/QPid (``rpc``), and Redis -- or you can define your own.
  703. No backend works well for every use case.
  704. You should read about the strengths and weaknesses of each backend, and choose
  705. the most appropriate for your needs.
  706. .. warning::
  707. Backends use resources to store and transmit results. To ensure
  708. that resources are released, you must eventually call
  709. :meth:`~@AsyncResult.get` or :meth:`~@AsyncResult.forget` on
  710. EVERY :class:`~@AsyncResult` instance returned after calling
  711. a task.
  712. .. seealso::
  713. :ref:`conf-result-backend`
  714. RPC Result Backend (RabbitMQ/QPid)
  715. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  716. The RPC result backend (`rpc://`) is special as it doesn't actually *store*
  717. the states, but rather sends them as messages. This is an important difference as it
  718. means that a result *can only be retrieved once*, and *only by the client
  719. that initiated the task*. Two different processes can't wait for the same result.
  720. Even with that limitation, it is an excellent choice if you need to receive
  721. state changes in real-time. Using messaging means the client doesn't have to
  722. poll for new states.
  723. The messages are transient (non-persistent) by default, so the results will
  724. disappear if the broker restarts. You can configure the result backend to send
  725. persistent messages using the :setting:`result_persistent` setting.
  726. Database Result Backend
  727. ~~~~~~~~~~~~~~~~~~~~~~~
  728. Keeping state in the database can be convenient for many, especially for
  729. web applications with a database already in place, but it also comes with
  730. limitations.
  731. * Polling the database for new states is expensive, and so you should
  732. increase the polling intervals of operations, such as `result.get()`.
  733. * Some databases use a default transaction isolation level that
  734. isn't suitable for polling tables for changes.
  735. In MySQL the default transaction isolation level is `REPEATABLE-READ`:
  736. meaning the transaction won't see changes made by other transactions until
  737. the current transaction is committed.
  738. Changing that to the `READ-COMMITTED` isolation level is recommended.
  739. .. _task-builtin-states:
  740. Built-in States
  741. ---------------
  742. .. state:: PENDING
  743. PENDING
  744. ~~~~~~~
  745. Task is waiting for execution or unknown.
  746. Any task id that's not known is implied to be in the pending state.
  747. .. state:: STARTED
  748. STARTED
  749. ~~~~~~~
  750. Task has been started.
  751. Not reported by default, to enable please see :attr:`@Task.track_started`.
  752. :meta-data: `pid` and `hostname` of the worker process executing
  753. the task.
  754. .. state:: SUCCESS
  755. SUCCESS
  756. ~~~~~~~
  757. Task has been successfully executed.
  758. :meta-data: `result` contains the return value of the task.
  759. :propagates: Yes
  760. :ready: Yes
  761. .. state:: FAILURE
  762. FAILURE
  763. ~~~~~~~
  764. Task execution resulted in failure.
  765. :meta-data: `result` contains the exception occurred, and `traceback`
  766. contains the backtrace of the stack at the point when the
  767. exception was raised.
  768. :propagates: Yes
  769. .. state:: RETRY
  770. RETRY
  771. ~~~~~
  772. Task is being retried.
  773. :meta-data: `result` contains the exception that caused the retry,
  774. and `traceback` contains the backtrace of the stack at the point
  775. when the exceptions was raised.
  776. :propagates: No
  777. .. state:: REVOKED
  778. REVOKED
  779. ~~~~~~~
  780. Task has been revoked.
  781. :propagates: Yes
  782. .. _custom-states:
  783. Custom states
  784. -------------
  785. You can easily define your own states, all you need is a unique name.
  786. The name of the state is usually an uppercase string. As an example
  787. you could have a look at the :mod:`abortable tasks <~celery.contrib.abortable>`
  788. which defines a custom :state:`ABORTED` state.
  789. Use :meth:`~@Task.update_state` to update a task's state:.
  790. .. code-block:: python
  791. @app.task(bind=True)
  792. def upload_files(self, filenames):
  793. for i, file in enumerate(filenames):
  794. if not self.request.called_directly:
  795. self.update_state(state='PROGRESS',
  796. meta={'current': i, 'total': len(filenames)})
  797. Here I created the state `"PROGRESS"`, telling any application
  798. aware of this state that the task is currently in progress, and also where
  799. it is in the process by having `current` and `total` counts as part of the
  800. state meta-data. This can then be used to create progress bars for example.
  801. .. _pickling_exceptions:
  802. Creating pickleable exceptions
  803. ------------------------------
  804. A rarely known Python fact is that exceptions must conform to some
  805. simple rules to support being serialized by the pickle module.
  806. Tasks that raise exceptions that aren't pickleable won't work
  807. properly when Pickle is used as the serializer.
  808. To make sure that your exceptions are pickleable the exception
  809. *MUST* provide the original arguments it was instantiated
  810. with in its ``.args`` attribute. The simplest way
  811. to ensure this is to have the exception call ``Exception.__init__``.
  812. Let's look at some examples that work, and one that doesn't:
  813. .. code-block:: python
  814. # OK:
  815. class HttpError(Exception):
  816. pass
  817. # BAD:
  818. class HttpError(Exception):
  819. def __init__(self, status_code):
  820. self.status_code = status_code
  821. # OK:
  822. class HttpError(Exception):
  823. def __init__(self, status_code):
  824. self.status_code = status_code
  825. Exception.__init__(self, status_code) # <-- REQUIRED
  826. So the rule is:
  827. For any exception that supports custom arguments ``*args``,
  828. ``Exception.__init__(self, *args)`` must be used.
  829. There's no special support for *keyword arguments*, so if you
  830. want to preserve keyword arguments when the exception is unpickled
  831. you have to pass them as regular args:
  832. .. code-block:: python
  833. class HttpError(Exception):
  834. def __init__(self, status_code, headers=None, body=None):
  835. self.status_code = status_code
  836. self.headers = headers
  837. self.body = body
  838. super(HttpError, self).__init__(status_code, headers, body)
  839. .. _task-semipredicates:
  840. Semipredicates
  841. ==============
  842. The worker wraps the task in a tracing function that records the final
  843. state of the task. There are a number of exceptions that can be used to
  844. signal this function to change how it treats the return of the task.
  845. .. _task-semipred-ignore:
  846. Ignore
  847. ------
  848. The task may raise :exc:`~@Ignore` to force the worker to ignore the
  849. task. This means that no state will be recorded for the task, but the
  850. message is still acknowledged (removed from queue).
  851. This can be used if you want to implement custom revoke-like
  852. functionality, or manually store the result of a task.
  853. Example keeping revoked tasks in a Redis set:
  854. .. code-block:: python
  855. from celery.exceptions import Ignore
  856. @app.task(bind=True)
  857. def some_task(self):
  858. if redis.ismember('tasks.revoked', self.request.id):
  859. raise Ignore()
  860. Example that stores results manually:
  861. .. code-block:: python
  862. from celery import states
  863. from celery.exceptions import Ignore
  864. @app.task(bind=True)
  865. def get_tweets(self, user):
  866. timeline = twitter.get_timeline(user)
  867. if not self.request.called_directly:
  868. self.update_state(state=states.SUCCESS, meta=timeline)
  869. raise Ignore()
  870. .. _task-semipred-reject:
  871. Reject
  872. ------
  873. The task may raise :exc:`~@Reject` to reject the task message using
  874. AMQPs ``basic_reject`` method. This won't have any effect unless
  875. :attr:`Task.acks_late` is enabled.
  876. Rejecting a message has the same effect as acking it, but some
  877. brokers may implement additional functionality that can be used.
  878. For example RabbitMQ supports the concept of `Dead Letter Exchanges`_
  879. where a queue can be configured to use a dead letter exchange that rejected
  880. messages are redelivered to.
  881. .. _`Dead Letter Exchanges`: http://www.rabbitmq.com/dlx.html
  882. Reject can also be used to re-queue messages, but please be very careful
  883. when using this as it can easily result in an infinite message loop.
  884. Example using reject when a task causes an out of memory condition:
  885. .. code-block:: python
  886. import errno
  887. from celery.exceptions import Reject
  888. @app.task(bind=True, acks_late=True)
  889. def render_scene(self, path):
  890. file = get_file(path)
  891. try:
  892. renderer.render_scene(file)
  893. # if the file is too big to fit in memory
  894. # we reject it so that it's redelivered to the dead letter exchange
  895. # and we can manually inspect the situation.
  896. except MemoryError as exc:
  897. raise Reject(exc, requeue=False)
  898. except OSError as exc:
  899. if exc.errno == errno.ENOMEM:
  900. raise Reject(exc, requeue=False)
  901. # For any other error we retry after 10 seconds.
  902. except Exception as exc:
  903. raise self.retry(exc, countdown=10)
  904. Example re-queuing the message:
  905. .. code-block:: python
  906. from celery.exceptions import Reject
  907. @app.task(bind=True, acks_late=True)
  908. def requeues(self):
  909. if not self.request.delivery_info['redelivered']:
  910. raise Reject('no reason', requeue=True)
  911. print('received two times')
  912. Consult your broker documentation for more details about the ``basic_reject``
  913. method.
  914. .. _task-semipred-retry:
  915. Retry
  916. -----
  917. The :exc:`~@Retry` exception is raised by the ``Task.retry`` method
  918. to tell the worker that the task is being retried.
  919. .. _task-custom-classes:
  920. Custom task classes
  921. ===================
  922. All tasks inherit from the :class:`@Task` class.
  923. The :meth:`~@Task.run` method becomes the task body.
  924. As an example, the following code,
  925. .. code-block:: python
  926. @app.task
  927. def add(x, y):
  928. return x + y
  929. will do roughly this behind the scenes:
  930. .. code-block:: python
  931. class _AddTask(app.Task):
  932. def run(self, x, y):
  933. return x + y
  934. add = app.tasks[_AddTask.name]
  935. Instantiation
  936. -------------
  937. A task is **not** instantiated for every request, but is registered
  938. in the task registry as a global instance.
  939. This means that the ``__init__`` constructor will only be called
  940. once per process, and that the task class is semantically closer to an
  941. Actor.
  942. If you have a task,
  943. .. code-block:: python
  944. from celery import Task
  945. class NaiveAuthenticateServer(Task):
  946. def __init__(self):
  947. self.users = {'george': 'password'}
  948. def run(self, username, password):
  949. try:
  950. return self.users[username] == password
  951. except KeyError:
  952. return False
  953. And you route every request to the same process, then it
  954. will keep state between requests.
  955. This can also be useful to cache resources,
  956. For example, a base Task class that caches a database connection:
  957. .. code-block:: python
  958. from celery import Task
  959. class DatabaseTask(Task):
  960. _db = None
  961. @property
  962. def db(self):
  963. if self._db is None:
  964. self._db = Database.connect()
  965. return self._db
  966. that can be added to tasks like this:
  967. .. code-block:: python
  968. @app.task(base=DatabaseTask)
  969. def process_rows():
  970. for row in process_rows.db.table.all():
  971. process_row(row)
  972. The ``db`` attribute of the ``process_rows`` task will then
  973. always stay the same in each process.
  974. Handlers
  975. --------
  976. .. method:: after_return(self, status, retval, task_id, args, kwargs, einfo)
  977. Handler called after the task returns.
  978. :param status: Current task state.
  979. :param retval: Task return value/exception.
  980. :param task_id: Unique id of the task.
  981. :param args: Original arguments for the task that returned.
  982. :param kwargs: Original keyword arguments for the task
  983. that returned.
  984. :keyword einfo: :class:`~billiard.einfo.ExceptionInfo`
  985. instance, containing the traceback (if any).
  986. The return value of this handler is ignored.
  987. .. method:: on_failure(self, exc, task_id, args, kwargs, einfo)
  988. This is run by the worker when the task fails.
  989. :param exc: The exception raised by the task.
  990. :param task_id: Unique id of the failed task.
  991. :param args: Original arguments for the task that failed.
  992. :param kwargs: Original keyword arguments for the task
  993. that failed.
  994. :keyword einfo: :class:`~billiard.einfo.ExceptionInfo`
  995. instance, containing the traceback.
  996. The return value of this handler is ignored.
  997. .. method:: on_retry(self, exc, task_id, args, kwargs, einfo)
  998. This is run by the worker when the task is to be retried.
  999. :param exc: The exception sent to :meth:`~@Task.retry`.
  1000. :param task_id: Unique id of the retried task.
  1001. :param args: Original arguments for the retried task.
  1002. :param kwargs: Original keyword arguments for the retried task.
  1003. :keyword einfo: :class:`~billiard.einfo.ExceptionInfo`
  1004. instance, containing the traceback.
  1005. The return value of this handler is ignored.
  1006. .. method:: on_success(self, retval, task_id, args, kwargs)
  1007. Run by the worker if the task executes successfully.
  1008. :param retval: The return value of the task.
  1009. :param task_id: Unique id of the executed task.
  1010. :param args: Original arguments for the executed task.
  1011. :param kwargs: Original keyword arguments for the executed task.
  1012. The return value of this handler is ignored.
  1013. .. _task-requests-and-custom-requests:
  1014. Requests and custom requests
  1015. ----------------------------
  1016. Upon receiving a message to run a task, the `worker <guide-workers>`:ref:
  1017. creates a `request <celery.worker.request.Request>`:class: to represent such
  1018. demand.
  1019. Custom task classes may override which request class to use by changing the
  1020. attribute `celery.app.task.Task.Request`:attr:. You may either assign the
  1021. custom request class itself, or its fully qualified name.
  1022. The request has several responsibilities. Custom request classes should cover
  1023. them all -- they are responsible to actually run and trace the task. We
  1024. strongly recommend to inherit from `celery.worker.request.Request`:class:.
  1025. When using the `pre-forking worker <worker-concurrency>`:ref:, the methods
  1026. `~celery.worker.request.Request.on_timeout`:meth: and
  1027. `~celery.worker.request.Request.on_failure`:meth: are executed in the main
  1028. worker process. An application may leverage such facility to detect failures
  1029. which are not detected using `celery.app.task.Task.on_failure`:meth:.
  1030. As an example, the following custom request detects and logs hard time
  1031. limits, and other failures.
  1032. .. code-block:: python
  1033. import logging
  1034. from celery.worker.request import Request
  1035. logger = logging.getLogger('my.package')
  1036. class MyRequest(Request):
  1037. 'A minimal custom request to log failures and hard time limits.'
  1038. def on_timeout(self, soft, timeout):
  1039. super(MyRequest, self).on_timeout(soft, timeout)
  1040. if not soft:
  1041. logger.warning(
  1042. 'A hard timeout was enforced for task %s',
  1043. self.task.name
  1044. )
  1045. def on_failure(self, exc_info, send_failed_event=True, return_ok=False):
  1046. super(Request, self).on_failure(
  1047. exc_info,
  1048. send_failed_event=send_failed_event,
  1049. return_ok=return_ok
  1050. )
  1051. logger.warning(
  1052. 'Failure detected for task %s',
  1053. self.task.name
  1054. )
  1055. class MyTask(Task):
  1056. Request = MyRequest # you can use a FQN 'my.package:MyRequest'
  1057. @app.task(base=MyTask)
  1058. def some_longrunning_task():
  1059. # use your imagination
  1060. .. _task-how-they-work:
  1061. How it works
  1062. ============
  1063. Here come the technical details. This part isn't something you need to know,
  1064. but you may be interested.
  1065. All defined tasks are listed in a registry. The registry contains
  1066. a list of task names and their task classes. You can investigate this registry
  1067. yourself:
  1068. .. code-block:: pycon
  1069. >>> from proj.celery import app
  1070. >>> app.tasks
  1071. {'celery.chord_unlock':
  1072. <@task: celery.chord_unlock>,
  1073. 'celery.backend_cleanup':
  1074. <@task: celery.backend_cleanup>,
  1075. 'celery.chord':
  1076. <@task: celery.chord>}
  1077. This is the list of tasks built into Celery. Note that tasks
  1078. will only be registered when the module they're defined in is imported.
  1079. The default loader imports any modules listed in the
  1080. :setting:`imports` setting.
  1081. The :meth:`@task` decorator is responsible for registering your task
  1082. in the applications task registry.
  1083. When tasks are sent, no actual function code is sent with it, just the name
  1084. of the task to execute. When the worker then receives the message it can look
  1085. up the name in its task registry to find the execution code.
  1086. This means that your workers should always be updated with the same software
  1087. as the client. This is a drawback, but the alternative is a technical
  1088. challenge that's yet to be solved.
  1089. .. _task-best-practices:
  1090. Tips and Best Practices
  1091. =======================
  1092. .. _task-ignore_results:
  1093. Ignore results you don't want
  1094. -----------------------------
  1095. If you don't care about the results of a task, be sure to set the
  1096. :attr:`~@Task.ignore_result` option, as storing results
  1097. wastes time and resources.
  1098. .. code-block:: python
  1099. @app.task(ignore_result=True)
  1100. def mytask():
  1101. something()
  1102. Results can even be disabled globally using the :setting:`task_ignore_result`
  1103. setting.
  1104. .. versionadded::4.2
  1105. Results can be enabled/disabled on a per-execution basis, by passing the ``ignore_result`` boolean parameter,
  1106. when calling ``apply_async`` or ``delay``.
  1107. .. code-block:: python
  1108. @app.task
  1109. def mytask(x, y):
  1110. return x + y
  1111. # No result will be stored
  1112. result = mytask.apply_async(1, 2, ignore_result=True)
  1113. print result.get() # -> None
  1114. # Result will be stored
  1115. result = mytask.apply_async(1, 2, ignore_result=False)
  1116. print result.get() # -> 3
  1117. By default tasks will *not ignore results* (``ignore_result=False``) when a result backend is configured.
  1118. The option precedence order is the following:
  1119. 1. Global :setting:`task_ignore_result`
  1120. 2. :attr:`~@Task.ignore_result` option
  1121. 3. Task execution option ``ignore_result``
  1122. More optimization tips
  1123. ----------------------
  1124. You find additional optimization tips in the
  1125. :ref:`Optimizing Guide <guide-optimizing>`.
  1126. .. _task-synchronous-subtasks:
  1127. Avoid launching synchronous subtasks
  1128. ------------------------------------
  1129. Having a task wait for the result of another task is really inefficient,
  1130. and may even cause a deadlock if the worker pool is exhausted.
  1131. Make your design asynchronous instead, for example by using *callbacks*.
  1132. **Bad**:
  1133. .. code-block:: python
  1134. @app.task
  1135. def update_page_info(url):
  1136. page = fetch_page.delay(url).get()
  1137. info = parse_page.delay(url, page).get()
  1138. store_page_info.delay(url, info)
  1139. @app.task
  1140. def fetch_page(url):
  1141. return myhttplib.get(url)
  1142. @app.task
  1143. def parse_page(url, page):
  1144. return myparser.parse_document(page)
  1145. @app.task
  1146. def store_page_info(url, info):
  1147. return PageInfo.objects.create(url, info)
  1148. **Good**:
  1149. .. code-block:: python
  1150. def update_page_info(url):
  1151. # fetch_page -> parse_page -> store_page
  1152. chain = fetch_page.s(url) | parse_page.s() | store_page_info.s(url)
  1153. chain()
  1154. @app.task()
  1155. def fetch_page(url):
  1156. return myhttplib.get(url)
  1157. @app.task()
  1158. def parse_page(page):
  1159. return myparser.parse_document(page)
  1160. @app.task(ignore_result=True)
  1161. def store_page_info(info, url):
  1162. PageInfo.objects.create(url=url, info=info)
  1163. Here I instead created a chain of tasks by linking together
  1164. different :func:`~celery.signature`'s.
  1165. You can read about chains and other powerful constructs
  1166. at :ref:`designing-workflows`.
  1167. By default Celery will not enable you to run tasks within task synchronously
  1168. in rare or extreme cases you might have to do so.
  1169. **WARNING**:
  1170. enabling subtasks run synchronously is not recommended!
  1171. .. code-block:: python
  1172. @app.task
  1173. def update_page_info(url):
  1174. page = fetch_page.delay(url).get(disable_sync_subtasks=False)
  1175. info = parse_page.delay(url, page).get(disable_sync_subtasks=False)
  1176. store_page_info.delay(url, info)
  1177. @app.task
  1178. def fetch_page(url):
  1179. return myhttplib.get(url)
  1180. @app.task
  1181. def parse_page(url, page):
  1182. return myparser.parse_document(page)
  1183. @app.task
  1184. def store_page_info(url, info):
  1185. return PageInfo.objects.create(url, info)
  1186. .. _task-performance-and-strategies:
  1187. Performance and Strategies
  1188. ==========================
  1189. .. _task-granularity:
  1190. Granularity
  1191. -----------
  1192. The task granularity is the amount of computation needed by each subtask.
  1193. In general it is better to split the problem up into many small tasks rather
  1194. than have a few long running tasks.
  1195. With smaller tasks you can process more tasks in parallel and the tasks
  1196. won't run long enough to block the worker from processing other waiting tasks.
  1197. However, executing a task does have overhead. A message needs to be sent, data
  1198. may not be local, etc. So if the tasks are too fine-grained the
  1199. overhead added probably removes any benefit.
  1200. .. seealso::
  1201. The book `Art of Concurrency`_ has a section dedicated to the topic
  1202. of task granularity [AOC1]_.
  1203. .. _`Art of Concurrency`: http://oreilly.com/catalog/9780596521547
  1204. .. [AOC1] Breshears, Clay. Section 2.2.1, "The Art of Concurrency".
  1205. O'Reilly Media, Inc. May 15, 2009. ISBN-13 978-0-596-52153-0.
  1206. .. _task-data-locality:
  1207. Data locality
  1208. -------------
  1209. The worker processing the task should be as close to the data as
  1210. possible. The best would be to have a copy in memory, the worst would be a
  1211. full transfer from another continent.
  1212. If the data is far away, you could try to run another worker at location, or
  1213. if that's not possible - cache often used data, or preload data you know
  1214. is going to be used.
  1215. The easiest way to share data between workers is to use a distributed cache
  1216. system, like `memcached`_.
  1217. .. seealso::
  1218. The paper `Distributed Computing Economics`_ by Jim Gray is an excellent
  1219. introduction to the topic of data locality.
  1220. .. _`Distributed Computing Economics`:
  1221. http://research.microsoft.com/pubs/70001/tr-2003-24.pdf
  1222. .. _`memcached`: http://memcached.org/
  1223. .. _task-state:
  1224. State
  1225. -----
  1226. Since Celery is a distributed system, you can't know which process, or
  1227. on what machine the task will be executed. You can't even know if the task will
  1228. run in a timely manner.
  1229. The ancient async sayings tells us that “asserting the world is the
  1230. responsibility of the task”. What this means is that the world view may
  1231. have changed since the task was requested, so the task is responsible for
  1232. making sure the world is how it should be; If you have a task
  1233. that re-indexes a search engine, and the search engine should only be
  1234. re-indexed at maximum every 5 minutes, then it must be the tasks
  1235. responsibility to assert that, not the callers.
  1236. Another gotcha is Django model objects. They shouldn't be passed on as
  1237. arguments to tasks. It's almost always better to re-fetch the object from
  1238. the database when the task is running instead, as using old data may lead
  1239. to race conditions.
  1240. Imagine the following scenario where you have an article and a task
  1241. that automatically expands some abbreviations in it:
  1242. .. code-block:: python
  1243. class Article(models.Model):
  1244. title = models.CharField()
  1245. body = models.TextField()
  1246. @app.task
  1247. def expand_abbreviations(article):
  1248. article.body.replace('MyCorp', 'My Corporation')
  1249. article.save()
  1250. First, an author creates an article and saves it, then the author
  1251. clicks on a button that initiates the abbreviation task:
  1252. .. code-block:: pycon
  1253. >>> article = Article.objects.get(id=102)
  1254. >>> expand_abbreviations.delay(article)
  1255. Now, the queue is very busy, so the task won't be run for another 2 minutes.
  1256. In the meantime another author makes changes to the article, so
  1257. when the task is finally run, the body of the article is reverted to the old
  1258. version because the task had the old body in its argument.
  1259. Fixing the race condition is easy, just use the article id instead, and
  1260. re-fetch the article in the task body:
  1261. .. code-block:: python
  1262. @app.task
  1263. def expand_abbreviations(article_id):
  1264. article = Article.objects.get(id=article_id)
  1265. article.body.replace('MyCorp', 'My Corporation')
  1266. article.save()
  1267. .. code-block:: pycon
  1268. >>> expand_abbreviations.delay(article_id)
  1269. There might even be performance benefits to this approach, as sending large
  1270. messages may be expensive.
  1271. .. _task-database-transactions:
  1272. Database transactions
  1273. ---------------------
  1274. Let's have a look at another example:
  1275. .. code-block:: python
  1276. from django.db import transaction
  1277. @transaction.commit_on_success
  1278. def create_article(request):
  1279. article = Article.objects.create()
  1280. expand_abbreviations.delay(article.pk)
  1281. This is a Django view creating an article object in the database,
  1282. then passing the primary key to a task. It uses the `commit_on_success`
  1283. decorator, that will commit the transaction when the view returns, or
  1284. roll back if the view raises an exception.
  1285. There's a race condition if the task starts executing
  1286. before the transaction has been committed; The database object doesn't exist
  1287. yet!
  1288. The solution is to use the ``on_commit`` callback to launch your Celery task
  1289. once all transactions have been committed successfully.
  1290. .. code-block:: python
  1291. from django.db.transaction import on_commit
  1292. def create_article(request):
  1293. article = Article.objects.create()
  1294. on_commit(lambda: expand_abbreviations.delay(article.pk))
  1295. .. note::
  1296. ``on_commit`` is available in Django 1.9 and above, if you are using a
  1297. version prior to that then the `django-transaction-hooks`_ library
  1298. adds support for this.
  1299. .. _`django-transaction-hooks`: https://github.com/carljm/django-transaction-hooks
  1300. .. _task-example:
  1301. Example
  1302. =======
  1303. Let's take a real world example: a blog where comments posted need to be
  1304. filtered for spam. When the comment is created, the spam filter runs in the
  1305. background, so the user doesn't have to wait for it to finish.
  1306. I have a Django blog application allowing comments
  1307. on blog posts. I'll describe parts of the models/views and tasks for this
  1308. application.
  1309. ``blog/models.py``
  1310. ------------------
  1311. The comment model looks like this:
  1312. .. code-block:: python
  1313. from django.db import models
  1314. from django.utils.translation import ugettext_lazy as _
  1315. class Comment(models.Model):
  1316. name = models.CharField(_('name'), max_length=64)
  1317. email_address = models.EmailField(_('email address'))
  1318. homepage = models.URLField(_('home page'),
  1319. blank=True, verify_exists=False)
  1320. comment = models.TextField(_('comment'))
  1321. pub_date = models.DateTimeField(_('Published date'),
  1322. editable=False, auto_add_now=True)
  1323. is_spam = models.BooleanField(_('spam?'),
  1324. default=False, editable=False)
  1325. class Meta:
  1326. verbose_name = _('comment')
  1327. verbose_name_plural = _('comments')
  1328. In the view where the comment is posted, I first write the comment
  1329. to the database, then I launch the spam filter task in the background.
  1330. .. _task-example-blog-views:
  1331. ``blog/views.py``
  1332. -----------------
  1333. .. code-block:: python
  1334. from django import forms
  1335. from django.http import HttpResponseRedirect
  1336. from django.template.context import RequestContext
  1337. from django.shortcuts import get_object_or_404, render_to_response
  1338. from blog import tasks
  1339. from blog.models import Comment
  1340. class CommentForm(forms.ModelForm):
  1341. class Meta:
  1342. model = Comment
  1343. def add_comment(request, slug, template_name='comments/create.html'):
  1344. post = get_object_or_404(Entry, slug=slug)
  1345. remote_addr = request.META.get('REMOTE_ADDR')
  1346. if request.method == 'post':
  1347. form = CommentForm(request.POST, request.FILES)
  1348. if form.is_valid():
  1349. comment = form.save()
  1350. # Check spam asynchronously.
  1351. tasks.spam_filter.delay(comment_id=comment.id,
  1352. remote_addr=remote_addr)
  1353. return HttpResponseRedirect(post.get_absolute_url())
  1354. else:
  1355. form = CommentForm()
  1356. context = RequestContext(request, {'form': form})
  1357. return render_to_response(template_name, context_instance=context)
  1358. To filter spam in comments I use `Akismet`_, the service
  1359. used to filter spam in comments posted to the free blog platform
  1360. `Wordpress`. `Akismet`_ is free for personal use, but for commercial use you
  1361. need to pay. You have to sign up to their service to get an API key.
  1362. To make API calls to `Akismet`_ I use the `akismet.py`_ library written by
  1363. `Michael Foord`_.
  1364. .. _task-example-blog-tasks:
  1365. ``blog/tasks.py``
  1366. -----------------
  1367. .. code-block:: python
  1368. from celery import Celery
  1369. from akismet import Akismet
  1370. from django.core.exceptions import ImproperlyConfigured
  1371. from django.contrib.sites.models import Site
  1372. from blog.models import Comment
  1373. app = Celery(broker='amqp://')
  1374. @app.task
  1375. def spam_filter(comment_id, remote_addr=None):
  1376. logger = spam_filter.get_logger()
  1377. logger.info('Running spam filter for comment %s', comment_id)
  1378. comment = Comment.objects.get(pk=comment_id)
  1379. current_domain = Site.objects.get_current().domain
  1380. akismet = Akismet(settings.AKISMET_KEY, 'http://{0}'.format(domain))
  1381. if not akismet.verify_key():
  1382. raise ImproperlyConfigured('Invalid AKISMET_KEY')
  1383. is_spam = akismet.comment_check(user_ip=remote_addr,
  1384. comment_content=comment.comment,
  1385. comment_author=comment.name,
  1386. comment_author_email=comment.email_address)
  1387. if is_spam:
  1388. comment.is_spam = True
  1389. comment.save()
  1390. return is_spam
  1391. .. _`Akismet`: http://akismet.com/faq/
  1392. .. _`akismet.py`: http://www.voidspace.org.uk/downloads/akismet.py
  1393. .. _`Michael Foord`: http://www.voidspace.org.uk/
  1394. .. _`exponential backoff`: https://en.wikipedia.org/wiki/Exponential_backoff
  1395. .. _`jitter`: https://en.wikipedia.org/wiki/Jitter