tasks.rst 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027
  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 you have 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. Hiding sensitive information in arguments
  387. -----------------------------------------
  388. .. versionadded:: 4.0
  389. When using :setting:`task_protocol` 2 or higher (default since 4.0), you can
  390. override how positional arguments and keyword arguments are represented in logs
  391. and monitoring events using the ``argsrepr`` and ``kwargsrepr`` calling
  392. arguments:
  393. .. code-block:: pycon
  394. >>> add.apply_async((2, 3), argsrepr='(<secret-x>, <secret-y>)')
  395. >>> charge.s(account, card='1234 5678 1234 5678').set(
  396. ... kwargsrepr=repr({'card': '**** **** **** 5678'})
  397. ... ).delay()
  398. .. warning::
  399. Sensitive information will still be accessible to anyone able
  400. to read your task message from the broker, or otherwise able intercept it.
  401. For this reason you should probably encrypt your message if it contains
  402. sensitive information, or in this example with a credit card number
  403. the actual number could be stored encrypted in a secure store that you retrieve
  404. and decrypt in the task itself.
  405. .. _task-retry:
  406. Retrying
  407. ========
  408. :meth:`Task.retry() <@Task.retry>` can be used to re-execute the task,
  409. for example in the event of recoverable errors.
  410. When you call ``retry`` it'll send a new message, using the same
  411. task-id, and it'll take care to make sure the message is delivered
  412. to the same queue as the originating task.
  413. When a task is retried this is also recorded as a task state,
  414. so that you can track the progress of the task using the result
  415. instance (see :ref:`task-states`).
  416. Here's an example using ``retry``:
  417. .. code-block:: python
  418. @app.task(bind=True)
  419. def send_twitter_status(self, oauth, tweet):
  420. try:
  421. twitter = Twitter(oauth)
  422. twitter.update_status(tweet)
  423. except (Twitter.FailWhaleError, Twitter.LoginError) as exc:
  424. raise self.retry(exc=exc)
  425. .. note::
  426. The :meth:`Task.retry() <@Task.retry>` call will raise an exception so any
  427. code after the retry won't be reached. This is the :exc:`~@Retry`
  428. exception, it isn't handled as an error but rather as a semi-predicate
  429. to signify to the worker that the task is to be retried,
  430. so that it can store the correct state when a result backend is enabled.
  431. This is normal operation and always happens unless the
  432. ``throw`` argument to retry is set to :const:`False`.
  433. The bind argument to the task decorator will give access to ``self`` (the
  434. task type instance).
  435. The ``exc`` method is used to pass exception information that's
  436. used in logs, and when storing task results.
  437. Both the exception and the traceback will
  438. be available in the task state (if a result backend is enabled).
  439. If the task has a ``max_retries`` value the current exception
  440. will be re-raised if the max number of retries has been exceeded,
  441. but this won't happen if:
  442. - An ``exc`` argument wasn't given.
  443. In this case the :exc:`~@MaxRetriesExceededError`
  444. exception will be raised.
  445. - There's no current exception
  446. If there's no original exception to re-raise the ``exc``
  447. argument will be used instead, so:
  448. .. code-block:: python
  449. self.retry(exc=Twitter.LoginError())
  450. will raise the ``exc`` argument given.
  451. .. _task-retry-custom-delay:
  452. Using a custom retry delay
  453. --------------------------
  454. When a task is to be retried, it can wait for a given amount of time
  455. before doing so, and the default delay is defined by the
  456. :attr:`~@Task.default_retry_delay`
  457. attribute. By default this is set to 3 minutes. Note that the
  458. unit for setting the delay is in seconds (int or float).
  459. You can also provide the `countdown` argument to :meth:`~@Task.retry` to
  460. override this default.
  461. .. code-block:: python
  462. @app.task(bind=True, default_retry_delay=30 * 60) # retry in 30 minutes.
  463. def add(self, x, y):
  464. try:
  465. something_raising()
  466. except Exception as exc:
  467. # overrides the default delay to retry after 1 minute
  468. raise self.retry(exc=exc, countdown=60)
  469. .. _task-autoretry:
  470. Automatic retry for known exceptions
  471. ------------------------------------
  472. .. versionadded:: 4.0
  473. Sometimes you just want to retry a task whenever a particular exception
  474. is raised.
  475. Fortunately, you can tell Celery to automatically retry a task using
  476. `autoretry_for` argument in `~@Celery.task` decorator:
  477. .. code-block:: python
  478. from twitter.exceptions import FailWhaleError
  479. @app.task(autoretry_for=(FailWhaleError,))
  480. def refresh_timeline(user):
  481. return twitter.refresh_timeline(user)
  482. If you want to specify custom arguments for internal `~@Task.retry`
  483. call, pass `retry_kwargs` argument to `~@Celery.task` decorator:
  484. .. code-block:: python
  485. @app.task(autoretry_for=(FailWhaleError,),
  486. retry_kwargs={'max_retries': 5})
  487. def refresh_timeline(user):
  488. return twitter.refresh_timeline(user)
  489. This is provided as an alternative to manually handling the exceptions,
  490. and the example above will do the same as wrapping the task body
  491. in a :keyword:`try` ... :keyword:`except` statement:
  492. .. code-block:: python
  493. @app.task
  494. def refresh_timeline(user):
  495. try:
  496. twitter.refresh_timeline(user)
  497. except FailWhaleError as exc:
  498. raise div.retry(exc=exc, max_retries=5)
  499. If you want to automatically retry on any error, simply use:
  500. .. code-block:: python
  501. @app.task(autoretry_for=(Exception,))
  502. def x():
  503. ...
  504. .. versionadded:: 4.1
  505. If your tasks depend on another service, like making a request to an API,
  506. then it's a good idea to use `exponential backoff`_ to avoid overwhelming the
  507. service with your requests. Fortunately, Celery's automatic retry support
  508. makes it easy. Just specify the :attr:`~Task.retry_backoff` argument, like this:
  509. .. code-block:: python
  510. from requests.exceptions import RequestException
  511. @app.task(autoretry_for=(RequestException,), retry_backoff=True)
  512. def x():
  513. ...
  514. By default, this exponential backoff will also introduce random jitter_ to
  515. avoid having all the tasks run at the same moment. It will also cap the
  516. maximum backoff delay to 10 minutes. All these settings can be customized
  517. via options documented below.
  518. .. attribute:: Task.autoretry_for
  519. A list/tuple of exception classes. If any of these exceptions are raised
  520. during the execution of the task, the task will automatically be retried.
  521. By default, no exceptions will be autoretried.
  522. .. attribute:: Task.retry_kwargs
  523. A dictionary. Use this to customize how autoretries are executed.
  524. Note that if you use the exponential backoff options below, the `countdown`
  525. task option will be determined by Celery's autoretry system, and any
  526. `countdown` included in this dictionary will be ignored.
  527. .. attribute:: Task.retry_backoff
  528. A boolean, or a number. If this option is set to ``True``, autoretries
  529. will be delayed following the rules of `exponential backoff`_. The first
  530. retry will have a delay of 1 second, the second retry will have a delay
  531. of 2 seconds, the third will delay 4 seconds, the fourth will delay 8
  532. seconds, and so on. (However, this delay value is modified by
  533. :attr:`~Task.retry_jitter`, if it is enabled.)
  534. If this option is set to a number, it is used as a
  535. delay factor. For example, if this option is set to ``3``, the first retry
  536. will delay 3 seconds, the second will delay 6 seconds, the third will
  537. delay 12 seconds, the fourth will delay 24 seconds, and so on. By default,
  538. this option is set to ``False``, and autoretries will not be delayed.
  539. .. attribute:: Task.retry_backoff_max
  540. A number. If ``retry_backoff`` is enabled, this option will set a maximum
  541. delay in seconds between task autoretries. By default, this option is set to ``600``,
  542. which is 10 minutes.
  543. .. attribute:: Task.retry_jitter
  544. A boolean. `Jitter`_ is used to introduce randomness into
  545. exponential backoff delays, to prevent all tasks in the queue from being
  546. executed simultaneously. If this option is set to ``True``, the delay
  547. value calculated by :attr:`~Task.retry_backoff` is treated as a maximum,
  548. and the actual delay value will be a random number between zero and that
  549. maximum. By default, this option is set to ``True``.
  550. .. _task-options:
  551. List of Options
  552. ===============
  553. The task decorator can take a number of options that change the way
  554. the task behaves, for example you can set the rate limit for a task
  555. using the :attr:`rate_limit` option.
  556. Any keyword argument passed to the task decorator will actually be set
  557. as an attribute of the resulting task class, and this is a list
  558. of the built-in attributes.
  559. General
  560. -------
  561. .. _task-general-options:
  562. .. attribute:: Task.name
  563. The name the task is registered as.
  564. You can set this name manually, or a name will be
  565. automatically generated using the module and class name.
  566. See also :ref:`task-names`.
  567. .. attribute:: Task.request
  568. If the task is being executed this will contain information
  569. about the current request. Thread local storage is used.
  570. See :ref:`task-request-info`.
  571. .. attribute:: Task.max_retries
  572. Only applies if the task calls ``self.retry`` or if the task is decorated
  573. with the :ref:`autoretry_for <task-autoretry>` argument.
  574. The maximum number of attempted retries before giving up.
  575. If the number of retries exceeds this value a :exc:`~@MaxRetriesExceededError`
  576. exception will be raised.
  577. .. note::
  578. You have to call :meth:`~@Task.retry`
  579. manually, as it won't automatically retry on exception..
  580. The default is ``3``.
  581. A value of :const:`None` will disable the retry limit and the
  582. task will retry forever until it succeeds.
  583. .. attribute:: Task.throws
  584. Optional tuple of expected error classes that shouldn't be regarded
  585. as an actual error.
  586. Errors in this list will be reported as a failure to the result backend,
  587. but the worker won't log the event as an error, and no traceback will
  588. be included.
  589. Example:
  590. .. code-block:: python
  591. @task(throws=(KeyError, HttpNotFound)):
  592. def get_foo():
  593. something()
  594. Error types:
  595. - Expected errors (in ``Task.throws``)
  596. Logged with severity ``INFO``, traceback excluded.
  597. - Unexpected errors
  598. Logged with severity ``ERROR``, with traceback included.
  599. .. attribute:: Task.default_retry_delay
  600. Default time in seconds before a retry of the task
  601. should be executed. Can be either :class:`int` or :class:`float`.
  602. Default is a three minute delay.
  603. .. attribute:: Task.rate_limit
  604. Set the rate limit for this task type (limits the number of tasks
  605. that can be run in a given time frame). Tasks will still complete when
  606. a rate limit is in effect, but it may take some time before it's allowed to
  607. start.
  608. If this is :const:`None` no rate limit is in effect.
  609. If it is an integer or float, it is interpreted as "tasks per second".
  610. The rate limits can be specified in seconds, minutes or hours
  611. by appending `"/s"`, `"/m"` or `"/h"` to the value. Tasks will be evenly
  612. distributed over the specified time frame.
  613. Example: `"100/m"` (hundred tasks a minute). This will enforce a minimum
  614. delay of 600ms between starting two tasks on the same worker instance.
  615. Default is the :setting:`task_default_rate_limit` setting:
  616. if not specified means rate limiting for tasks is disabled by default.
  617. Note that this is a *per worker instance* rate limit, and not a global
  618. rate limit. To enforce a global rate limit (e.g., for an API with a
  619. maximum number of requests per second), you must restrict to a given
  620. queue.
  621. .. note::
  622. This attribute is ignored if the task is requested with an ETA.
  623. .. attribute:: Task.time_limit
  624. The hard time limit, in seconds, for this task.
  625. When not set the workers default is used.
  626. .. attribute:: Task.soft_time_limit
  627. The soft time limit for this task.
  628. When not set the workers default is used.
  629. .. attribute:: Task.ignore_result
  630. Don't store task state. Note that this means you can't use
  631. :class:`~celery.result.AsyncResult` to check if the task is ready,
  632. or get its return value.
  633. .. attribute:: Task.store_errors_even_if_ignored
  634. If :const:`True`, errors will be stored even if the task is configured
  635. to ignore results.
  636. .. attribute:: Task.serializer
  637. A string identifying the default serialization
  638. method to use. Defaults to the :setting:`task_serializer`
  639. setting. Can be `pickle`, `json`, `yaml`, or any custom
  640. serialization methods that have been registered with
  641. :mod:`kombu.serialization.registry`.
  642. Please see :ref:`calling-serializers` for more information.
  643. .. attribute:: Task.compression
  644. A string identifying the default compression scheme to use.
  645. Defaults to the :setting:`task_compression` setting.
  646. Can be `gzip`, or `bzip2`, or any custom compression schemes
  647. that have been registered with the :mod:`kombu.compression` registry.
  648. Please see :ref:`calling-compression` for more information.
  649. .. attribute:: Task.backend
  650. The result store backend to use for this task. An instance of one of the
  651. backend classes in `celery.backends`. Defaults to `app.backend`,
  652. defined by the :setting:`result_backend` setting.
  653. .. attribute:: Task.acks_late
  654. If set to :const:`True` messages for this task will be acknowledged
  655. **after** the task has been executed, not *just before* (the default
  656. behavior).
  657. Note: This means the task may be executed multiple times should the worker
  658. crash in the middle of execution. Make sure your tasks are
  659. :term:`idempotent`.
  660. The global default can be overridden by the :setting:`task_acks_late`
  661. setting.
  662. .. _task-track-started:
  663. .. attribute:: Task.track_started
  664. If :const:`True` the task will report its status as "started"
  665. when the task is executed by a worker.
  666. The default value is :const:`False` as the normal behavior is to not
  667. report that level of granularity. Tasks are either pending, finished,
  668. or waiting to be retried. Having a "started" status can be useful for
  669. when there are long running tasks and there's a need to report what
  670. task is currently running.
  671. The host name and process id of the worker executing the task
  672. will be available in the state meta-data (e.g., `result.info['pid']`)
  673. The global default can be overridden by the
  674. :setting:`task_track_started` setting.
  675. .. seealso::
  676. The API reference for :class:`~@Task`.
  677. .. _task-states:
  678. States
  679. ======
  680. Celery can keep track of the tasks current state. The state also contains the
  681. result of a successful task, or the exception and traceback information of a
  682. failed task.
  683. There are several *result backends* to choose from, and they all have
  684. different strengths and weaknesses (see :ref:`task-result-backends`).
  685. During its lifetime a task will transition through several possible states,
  686. and each state may have arbitrary meta-data attached to it. When a task
  687. moves into a new state the previous state is
  688. forgotten about, but some transitions can be deducted, (e.g., a task now
  689. in the :state:`FAILED` state, is implied to have been in the
  690. :state:`STARTED` state at some point).
  691. There are also sets of states, like the set of
  692. :state:`FAILURE_STATES`, and the set of :state:`READY_STATES`.
  693. The client uses the membership of these sets to decide whether
  694. the exception should be re-raised (:state:`PROPAGATE_STATES`), or whether
  695. the state can be cached (it can if the task is ready).
  696. You can also define :ref:`custom-states`.
  697. .. _task-result-backends:
  698. Result Backends
  699. ---------------
  700. If you want to keep track of tasks or need the return values, then Celery
  701. must store or send the states somewhere so that they can be retrieved later.
  702. There are several built-in result backends to choose from: SQLAlchemy/Django ORM,
  703. Memcached, RabbitMQ/QPid (``rpc``), and Redis -- or you can define your own.
  704. No backend works well for every use case.
  705. You should read about the strengths and weaknesses of each backend, and choose
  706. the most appropriate for your needs.
  707. .. seealso::
  708. :ref:`conf-result-backend`
  709. RPC Result Backend (RabbitMQ/QPid)
  710. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  711. The RPC result backend (`rpc://`) is special as it doesn't actually *store*
  712. the states, but rather sends them as messages. This is an important difference as it
  713. means that a result *can only be retrieved once*, and *only by the client
  714. that initiated the task*. Two different processes can't wait for the same result.
  715. Even with that limitation, it is an excellent choice if you need to receive
  716. state changes in real-time. Using messaging means the client doesn't have to
  717. poll for new states.
  718. The messages are transient (non-persistent) by default, so the results will
  719. disappear if the broker restarts. You can configure the result backend to send
  720. persistent messages using the :setting:`result_persistent` setting.
  721. Database Result Backend
  722. ~~~~~~~~~~~~~~~~~~~~~~~
  723. Keeping state in the database can be convenient for many, especially for
  724. web applications with a database already in place, but it also comes with
  725. limitations.
  726. * Polling the database for new states is expensive, and so you should
  727. increase the polling intervals of operations, such as `result.get()`.
  728. * Some databases use a default transaction isolation level that
  729. isn't suitable for polling tables for changes.
  730. In MySQL the default transaction isolation level is `REPEATABLE-READ`:
  731. meaning the transaction won't see changes made by other transactions until
  732. the current transaction is committed.
  733. Changing that to the `READ-COMMITTED` isolation level is recommended.
  734. .. _task-builtin-states:
  735. Built-in States
  736. ---------------
  737. .. state:: PENDING
  738. PENDING
  739. ~~~~~~~
  740. Task is waiting for execution or unknown.
  741. Any task id that's not known is implied to be in the pending state.
  742. .. state:: STARTED
  743. STARTED
  744. ~~~~~~~
  745. Task has been started.
  746. Not reported by default, to enable please see :attr:`@Task.track_started`.
  747. :meta-data: `pid` and `hostname` of the worker process executing
  748. the task.
  749. .. state:: SUCCESS
  750. SUCCESS
  751. ~~~~~~~
  752. Task has been successfully executed.
  753. :meta-data: `result` contains the return value of the task.
  754. :propagates: Yes
  755. :ready: Yes
  756. .. state:: FAILURE
  757. FAILURE
  758. ~~~~~~~
  759. Task execution resulted in failure.
  760. :meta-data: `result` contains the exception occurred, and `traceback`
  761. contains the backtrace of the stack at the point when the
  762. exception was raised.
  763. :propagates: Yes
  764. .. state:: RETRY
  765. RETRY
  766. ~~~~~
  767. Task is being retried.
  768. :meta-data: `result` contains the exception that caused the retry,
  769. and `traceback` contains the backtrace of the stack at the point
  770. when the exceptions was raised.
  771. :propagates: No
  772. .. state:: REVOKED
  773. REVOKED
  774. ~~~~~~~
  775. Task has been revoked.
  776. :propagates: Yes
  777. .. _custom-states:
  778. Custom states
  779. -------------
  780. You can easily define your own states, all you need is a unique name.
  781. The name of the state is usually an uppercase string. As an example
  782. you could have a look at the :mod:`abortable tasks <~celery.contrib.abortable>`
  783. which defines a custom :state:`ABORTED` state.
  784. Use :meth:`~@Task.update_state` to update a task's state:.
  785. .. code-block:: python
  786. @app.task(bind=True)
  787. def upload_files(self, filenames):
  788. for i, file in enumerate(filenames):
  789. if not self.request.called_directly:
  790. self.update_state(state='PROGRESS',
  791. meta={'current': i, 'total': len(filenames)})
  792. Here I created the state `"PROGRESS"`, telling any application
  793. aware of this state that the task is currently in progress, and also where
  794. it is in the process by having `current` and `total` counts as part of the
  795. state meta-data. This can then be used to create progress bars for example.
  796. .. _pickling_exceptions:
  797. Creating pickleable exceptions
  798. ------------------------------
  799. A rarely known Python fact is that exceptions must conform to some
  800. simple rules to support being serialized by the pickle module.
  801. Tasks that raise exceptions that aren't pickleable won't work
  802. properly when Pickle is used as the serializer.
  803. To make sure that your exceptions are pickleable the exception
  804. *MUST* provide the original arguments it was instantiated
  805. with in its ``.args`` attribute. The simplest way
  806. to ensure this is to have the exception call ``Exception.__init__``.
  807. Let's look at some examples that work, and one that doesn't:
  808. .. code-block:: python
  809. # OK:
  810. class HttpError(Exception):
  811. pass
  812. # BAD:
  813. class HttpError(Exception):
  814. def __init__(self, status_code):
  815. self.status_code = status_code
  816. # OK:
  817. class HttpError(Exception):
  818. def __init__(self, status_code):
  819. self.status_code = status_code
  820. Exception.__init__(self, status_code) # <-- REQUIRED
  821. So the rule is:
  822. For any exception that supports custom arguments ``*args``,
  823. ``Exception.__init__(self, *args)`` must be used.
  824. There's no special support for *keyword arguments*, so if you
  825. want to preserve keyword arguments when the exception is unpickled
  826. you have to pass them as regular args:
  827. .. code-block:: python
  828. class HttpError(Exception):
  829. def __init__(self, status_code, headers=None, body=None):
  830. self.status_code = status_code
  831. self.headers = headers
  832. self.body = body
  833. super(HttpError, self).__init__(status_code, headers, body)
  834. .. _task-semipredicates:
  835. Semipredicates
  836. ==============
  837. The worker wraps the task in a tracing function that records the final
  838. state of the task. There are a number of exceptions that can be used to
  839. signal this function to change how it treats the return of the task.
  840. .. _task-semipred-ignore:
  841. Ignore
  842. ------
  843. The task may raise :exc:`~@Ignore` to force the worker to ignore the
  844. task. This means that no state will be recorded for the task, but the
  845. message is still acknowledged (removed from queue).
  846. This can be used if you want to implement custom revoke-like
  847. functionality, or manually store the result of a task.
  848. Example keeping revoked tasks in a Redis set:
  849. .. code-block:: python
  850. from celery.exceptions import Ignore
  851. @app.task(bind=True)
  852. def some_task(self):
  853. if redis.ismember('tasks.revoked', self.request.id):
  854. raise Ignore()
  855. Example that stores results manually:
  856. .. code-block:: python
  857. from celery import states
  858. from celery.exceptions import Ignore
  859. @app.task(bind=True)
  860. def get_tweets(self, user):
  861. timeline = twitter.get_timeline(user)
  862. if not self.request.called_directly:
  863. self.update_state(state=states.SUCCESS, meta=timeline)
  864. raise Ignore()
  865. .. _task-semipred-reject:
  866. Reject
  867. ------
  868. The task may raise :exc:`~@Reject` to reject the task message using
  869. AMQPs ``basic_reject`` method. This won't have any effect unless
  870. :attr:`Task.acks_late` is enabled.
  871. Rejecting a message has the same effect as acking it, but some
  872. brokers may implement additional functionality that can be used.
  873. For example RabbitMQ supports the concept of `Dead Letter Exchanges`_
  874. where a queue can be configured to use a dead letter exchange that rejected
  875. messages are redelivered to.
  876. .. _`Dead Letter Exchanges`: http://www.rabbitmq.com/dlx.html
  877. Reject can also be used to re-queue messages, but please be very careful
  878. when using this as it can easily result in an infinite message loop.
  879. Example using reject when a task causes an out of memory condition:
  880. .. code-block:: python
  881. import errno
  882. from celery.exceptions import Reject
  883. @app.task(bind=True, acks_late=True)
  884. def render_scene(self, path):
  885. file = get_file(path)
  886. try:
  887. renderer.render_scene(file)
  888. # if the file is too big to fit in memory
  889. # we reject it so that it's redelivered to the dead letter exchange
  890. # and we can manually inspect the situation.
  891. except MemoryError as exc:
  892. raise Reject(exc, requeue=False)
  893. except OSError as exc:
  894. if exc.errno == errno.ENOMEM:
  895. raise Reject(exc, requeue=False)
  896. # For any other error we retry after 10 seconds.
  897. except Exception as exc:
  898. raise self.retry(exc, countdown=10)
  899. Example re-queuing the message:
  900. .. code-block:: python
  901. from celery.exceptions import Reject
  902. @app.task(bind=True, acks_late=True)
  903. def requeues(self):
  904. if not self.request.delivery_info['redelivered']:
  905. raise Reject('no reason', requeue=True)
  906. print('received two times')
  907. Consult your broker documentation for more details about the ``basic_reject``
  908. method.
  909. .. _task-semipred-retry:
  910. Retry
  911. -----
  912. The :exc:`~@Retry` exception is raised by the ``Task.retry`` method
  913. to tell the worker that the task is being retried.
  914. .. _task-custom-classes:
  915. Custom task classes
  916. ===================
  917. All tasks inherit from the :class:`@Task` class.
  918. The :meth:`~@Task.run` method becomes the task body.
  919. As an example, the following code,
  920. .. code-block:: python
  921. @app.task
  922. def add(x, y):
  923. return x + y
  924. will do roughly this behind the scenes:
  925. .. code-block:: python
  926. class _AddTask(app.Task):
  927. def run(self, x, y):
  928. return x + y
  929. add = app.tasks[_AddTask.name]
  930. Instantiation
  931. -------------
  932. A task is **not** instantiated for every request, but is registered
  933. in the task registry as a global instance.
  934. This means that the ``__init__`` constructor will only be called
  935. once per process, and that the task class is semantically closer to an
  936. Actor.
  937. If you have a task,
  938. .. code-block:: python
  939. from celery import Task
  940. class NaiveAuthenticateServer(Task):
  941. def __init__(self):
  942. self.users = {'george': 'password'}
  943. def run(self, username, password):
  944. try:
  945. return self.users[username] == password
  946. except KeyError:
  947. return False
  948. And you route every request to the same process, then it
  949. will keep state between requests.
  950. This can also be useful to cache resources,
  951. For example, a base Task class that caches a database connection:
  952. .. code-block:: python
  953. from celery import Task
  954. class DatabaseTask(Task):
  955. _db = None
  956. @property
  957. def db(self):
  958. if self._db is None:
  959. self._db = Database.connect()
  960. return self._db
  961. that can be added to tasks like this:
  962. .. code-block:: python
  963. @app.task(base=DatabaseTask)
  964. def process_rows():
  965. for row in process_rows.db.table.all():
  966. process_row(row)
  967. The ``db`` attribute of the ``process_rows`` task will then
  968. always stay the same in each process.
  969. Handlers
  970. --------
  971. .. method:: after_return(self, status, retval, task_id, args, kwargs, einfo)
  972. Handler called after the task returns.
  973. :param status: Current task state.
  974. :param retval: Task return value/exception.
  975. :param task_id: Unique id of the task.
  976. :param args: Original arguments for the task that returned.
  977. :param kwargs: Original keyword arguments for the task
  978. that returned.
  979. :keyword einfo: :class:`~billiard.einfo.ExceptionInfo`
  980. instance, containing the traceback (if any).
  981. The return value of this handler is ignored.
  982. .. method:: on_failure(self, exc, task_id, args, kwargs, einfo)
  983. This is run by the worker when the task fails.
  984. :param exc: The exception raised by the task.
  985. :param task_id: Unique id of the failed task.
  986. :param args: Original arguments for the task that failed.
  987. :param kwargs: Original keyword arguments for the task
  988. that failed.
  989. :keyword einfo: :class:`~billiard.einfo.ExceptionInfo`
  990. instance, containing the traceback.
  991. The return value of this handler is ignored.
  992. .. method:: on_retry(self, exc, task_id, args, kwargs, einfo)
  993. This is run by the worker when the task is to be retried.
  994. :param exc: The exception sent to :meth:`~@Task.retry`.
  995. :param task_id: Unique id of the retried task.
  996. :param args: Original arguments for the retried task.
  997. :param kwargs: Original keyword arguments for the retried task.
  998. :keyword einfo: :class:`~billiard.einfo.ExceptionInfo`
  999. instance, containing the traceback.
  1000. The return value of this handler is ignored.
  1001. .. method:: on_success(self, retval, task_id, args, kwargs)
  1002. Run by the worker if the task executes successfully.
  1003. :param retval: The return value of the task.
  1004. :param task_id: Unique id of the executed task.
  1005. :param args: Original arguments for the executed task.
  1006. :param kwargs: Original keyword arguments for the executed task.
  1007. The return value of this handler is ignored.
  1008. Requests and custom requests
  1009. ----------------------------
  1010. Upon receiving a message to run a task, the `worker <guide-workers>`:ref:
  1011. creates a `request <celery.worker.request.Request>`:class: to represent such
  1012. demand.
  1013. Custom task classes may override which request class to use by changing the
  1014. attribute `celery.app.task.Task.Request`:attr:. You may either assign the
  1015. custom request class itself, or its fully qualified name.
  1016. The request has several responsibilities. Custom request classes should cover
  1017. them all -- they are responsible to actually run and trace the task. We
  1018. strongly recommend to inherit from `celery.worker.request.Request`:class:.
  1019. When using the `pre-forking worker <worker-concurrency>`:ref:, the methods
  1020. `~celery.worker.request.Request.on_timeout`:meth: and
  1021. `~celery.worker.request.Request.on_failure`:meth: are executed in the main
  1022. worker process. An application may leverage such facility to detect failures
  1023. which are not detected using `celery.app.task.Task.on_failure`:meth:.
  1024. As an example, the following custom request detects and logs hard time
  1025. limits, and other failures.
  1026. .. code-block:: python
  1027. import logging
  1028. from celery.worker.request import Request
  1029. logger = logging.getLogger('my.package')
  1030. class MyRequest(Request):
  1031. 'A minimal custom request to log failures and hard time limits.'
  1032. def on_timeout(self, soft, timeout):
  1033. super(MyRequest, self).on_timeout(soft, timeout)
  1034. if not soft:
  1035. logger.warning(
  1036. 'A hard timeout was enforced for task %s',
  1037. self.task.name
  1038. )
  1039. def on_failure(self, exc_info, send_failed_event=True, return_ok=False):
  1040. super(Request, self).on_failure(
  1041. exc_info,
  1042. send_failed_event=send_failed_event,
  1043. return_ok=return_ok
  1044. )
  1045. logger.warning(
  1046. 'Failure detected for task %s',
  1047. self.task.name
  1048. )
  1049. class MyTask(Task):
  1050. Request = MyRequest # you can use a FQN 'my.package:MyRequest'
  1051. @app.task(base=MyTask)
  1052. def some_longrunning_task():
  1053. # use your imagination
  1054. .. _task-how-they-work:
  1055. How it works
  1056. ============
  1057. Here come the technical details. This part isn't something you need to know,
  1058. but you may be interested.
  1059. All defined tasks are listed in a registry. The registry contains
  1060. a list of task names and their task classes. You can investigate this registry
  1061. yourself:
  1062. .. code-block:: pycon
  1063. >>> from proj.celery import app
  1064. >>> app.tasks
  1065. {'celery.chord_unlock':
  1066. <@task: celery.chord_unlock>,
  1067. 'celery.backend_cleanup':
  1068. <@task: celery.backend_cleanup>,
  1069. 'celery.chord':
  1070. <@task: celery.chord>}
  1071. This is the list of tasks built-in to Celery. Note that tasks
  1072. will only be registered when the module they're defined in is imported.
  1073. The default loader imports any modules listed in the
  1074. :setting:`imports` setting.
  1075. The :meth:`@task` decorator is responsible for registering your task
  1076. in the applications task registry.
  1077. When tasks are sent, no actual function code is sent with it, just the name
  1078. of the task to execute. When the worker then receives the message it can look
  1079. up the name in its task registry to find the execution code.
  1080. This means that your workers should always be updated with the same software
  1081. as the client. This is a drawback, but the alternative is a technical
  1082. challenge that's yet to be solved.
  1083. .. _task-best-practices:
  1084. Tips and Best Practices
  1085. =======================
  1086. .. _task-ignore_results:
  1087. Ignore results you don't want
  1088. -----------------------------
  1089. If you don't care about the results of a task, be sure to set the
  1090. :attr:`~@Task.ignore_result` option, as storing results
  1091. wastes time and resources.
  1092. .. code-block:: python
  1093. @app.task(ignore_result=True)
  1094. def mytask():
  1095. something()
  1096. Results can even be disabled globally using the :setting:`task_ignore_result`
  1097. setting.
  1098. More optimization tips
  1099. ----------------------
  1100. You find additional optimization tips in the
  1101. :ref:`Optimizing Guide <guide-optimizing>`.
  1102. .. _task-synchronous-subtasks:
  1103. Avoid launching synchronous subtasks
  1104. ------------------------------------
  1105. Having a task wait for the result of another task is really inefficient,
  1106. and may even cause a deadlock if the worker pool is exhausted.
  1107. Make your design asynchronous instead, for example by using *callbacks*.
  1108. **Bad**:
  1109. .. code-block:: python
  1110. @app.task
  1111. def update_page_info(url):
  1112. page = fetch_page.delay(url).get()
  1113. info = parse_page.delay(url, page).get()
  1114. store_page_info.delay(url, info)
  1115. @app.task
  1116. def fetch_page(url):
  1117. return myhttplib.get(url)
  1118. @app.task
  1119. def parse_page(url, page):
  1120. return myparser.parse_document(page)
  1121. @app.task
  1122. def store_page_info(url, info):
  1123. return PageInfo.objects.create(url, info)
  1124. **Good**:
  1125. .. code-block:: python
  1126. def update_page_info(url):
  1127. # fetch_page -> parse_page -> store_page
  1128. chain = fetch_page.s(url) | parse_page.s() | store_page_info.s(url)
  1129. chain()
  1130. @app.task()
  1131. def fetch_page(url):
  1132. return myhttplib.get(url)
  1133. @app.task()
  1134. def parse_page(page):
  1135. return myparser.parse_document(page)
  1136. @app.task(ignore_result=True)
  1137. def store_page_info(info, url):
  1138. PageInfo.objects.create(url=url, info=info)
  1139. Here I instead created a chain of tasks by linking together
  1140. different :func:`~celery.signature`'s.
  1141. You can read about chains and other powerful constructs
  1142. at :ref:`designing-workflows`.
  1143. By default celery will not enable you to run tasks within task synchronously
  1144. in rare or extreme cases you might have to do so.
  1145. **WARNING**:
  1146. enabling subtasks run synchronously is not recommended!
  1147. .. code-block:: python
  1148. @app.task
  1149. def update_page_info(url):
  1150. page = fetch_page.delay(url).get(disable_sync_subtasks=False)
  1151. info = parse_page.delay(url, page).get(disable_sync_subtasks=False)
  1152. store_page_info.delay(url, info)
  1153. @app.task
  1154. def fetch_page(url):
  1155. return myhttplib.get(url)
  1156. @app.task
  1157. def parse_page(url, page):
  1158. return myparser.parse_document(page)
  1159. @app.task
  1160. def store_page_info(url, info):
  1161. return PageInfo.objects.create(url, info)
  1162. .. _task-performance-and-strategies:
  1163. Performance and Strategies
  1164. ==========================
  1165. .. _task-granularity:
  1166. Granularity
  1167. -----------
  1168. The task granularity is the amount of computation needed by each subtask.
  1169. In general it is better to split the problem up into many small tasks rather
  1170. than have a few long running tasks.
  1171. With smaller tasks you can process more tasks in parallel and the tasks
  1172. won't run long enough to block the worker from processing other waiting tasks.
  1173. However, executing a task does have overhead. A message needs to be sent, data
  1174. may not be local, etc. So if the tasks are too fine-grained the
  1175. overhead added probably removes any benefit.
  1176. .. seealso::
  1177. The book `Art of Concurrency`_ has a section dedicated to the topic
  1178. of task granularity [AOC1]_.
  1179. .. _`Art of Concurrency`: http://oreilly.com/catalog/9780596521547
  1180. .. [AOC1] Breshears, Clay. Section 2.2.1, "The Art of Concurrency".
  1181. O'Reilly Media, Inc. May 15, 2009. ISBN-13 978-0-596-52153-0.
  1182. .. _task-data-locality:
  1183. Data locality
  1184. -------------
  1185. The worker processing the task should be as close to the data as
  1186. possible. The best would be to have a copy in memory, the worst would be a
  1187. full transfer from another continent.
  1188. If the data is far away, you could try to run another worker at location, or
  1189. if that's not possible - cache often used data, or preload data you know
  1190. is going to be used.
  1191. The easiest way to share data between workers is to use a distributed cache
  1192. system, like `memcached`_.
  1193. .. seealso::
  1194. The paper `Distributed Computing Economics`_ by Jim Gray is an excellent
  1195. introduction to the topic of data locality.
  1196. .. _`Distributed Computing Economics`:
  1197. http://research.microsoft.com/pubs/70001/tr-2003-24.pdf
  1198. .. _`memcached`: http://memcached.org/
  1199. .. _task-state:
  1200. State
  1201. -----
  1202. Since celery is a distributed system, you can't know which process, or
  1203. on what machine the task will be executed. You can't even know if the task will
  1204. run in a timely manner.
  1205. The ancient async sayings tells us that “asserting the world is the
  1206. responsibility of the task”. What this means is that the world view may
  1207. have changed since the task was requested, so the task is responsible for
  1208. making sure the world is how it should be; If you have a task
  1209. that re-indexes a search engine, and the search engine should only be
  1210. re-indexed at maximum every 5 minutes, then it must be the tasks
  1211. responsibility to assert that, not the callers.
  1212. Another gotcha is Django model objects. They shouldn't be passed on as
  1213. arguments to tasks. It's almost always better to re-fetch the object from
  1214. the database when the task is running instead, as using old data may lead
  1215. to race conditions.
  1216. Imagine the following scenario where you have an article and a task
  1217. that automatically expands some abbreviations in it:
  1218. .. code-block:: python
  1219. class Article(models.Model):
  1220. title = models.CharField()
  1221. body = models.TextField()
  1222. @app.task
  1223. def expand_abbreviations(article):
  1224. article.body.replace('MyCorp', 'My Corporation')
  1225. article.save()
  1226. First, an author creates an article and saves it, then the author
  1227. clicks on a button that initiates the abbreviation task:
  1228. .. code-block:: pycon
  1229. >>> article = Article.objects.get(id=102)
  1230. >>> expand_abbreviations.delay(article)
  1231. Now, the queue is very busy, so the task won't be run for another 2 minutes.
  1232. In the meantime another author makes changes to the article, so
  1233. when the task is finally run, the body of the article is reverted to the old
  1234. version because the task had the old body in its argument.
  1235. Fixing the race condition is easy, just use the article id instead, and
  1236. re-fetch the article in the task body:
  1237. .. code-block:: python
  1238. @app.task
  1239. def expand_abbreviations(article_id):
  1240. article = Article.objects.get(id=article_id)
  1241. article.body.replace('MyCorp', 'My Corporation')
  1242. article.save()
  1243. .. code-block:: pycon
  1244. >>> expand_abbreviations.delay(article_id)
  1245. There might even be performance benefits to this approach, as sending large
  1246. messages may be expensive.
  1247. .. _task-database-transactions:
  1248. Database transactions
  1249. ---------------------
  1250. Let's have a look at another example:
  1251. .. code-block:: python
  1252. from django.db import transaction
  1253. @transaction.commit_on_success
  1254. def create_article(request):
  1255. article = Article.objects.create()
  1256. expand_abbreviations.delay(article.pk)
  1257. This is a Django view creating an article object in the database,
  1258. then passing the primary key to a task. It uses the `commit_on_success`
  1259. decorator, that will commit the transaction when the view returns, or
  1260. roll back if the view raises an exception.
  1261. There's a race condition if the task starts executing
  1262. before the transaction has been committed; The database object doesn't exist
  1263. yet!
  1264. The solution is to use the ``on_commit`` callback to launch your celery task
  1265. once all transactions have been committed successfully.
  1266. .. code-block:: python
  1267. from django.db.transaction import on_commit
  1268. def create_article(request):
  1269. article = Article.objects.create()
  1270. on_commit(lambda: expand_abbreviations.delay(article.pk))
  1271. .. note::
  1272. ``on_commit`` is available in Django 1.9 and above, if you are using a
  1273. version prior to that then the `django-transaction-hooks`_ library
  1274. adds support for this.
  1275. .. _`django-transaction-hooks`: https://github.com/carljm/django-transaction-hooks
  1276. .. _task-example:
  1277. Example
  1278. =======
  1279. Let's take a real world example: a blog where comments posted need to be
  1280. filtered for spam. When the comment is created, the spam filter runs in the
  1281. background, so the user doesn't have to wait for it to finish.
  1282. I have a Django blog application allowing comments
  1283. on blog posts. I'll describe parts of the models/views and tasks for this
  1284. application.
  1285. ``blog/models.py``
  1286. ------------------
  1287. The comment model looks like this:
  1288. .. code-block:: python
  1289. from django.db import models
  1290. from django.utils.translation import ugettext_lazy as _
  1291. class Comment(models.Model):
  1292. name = models.CharField(_('name'), max_length=64)
  1293. email_address = models.EmailField(_('email address'))
  1294. homepage = models.URLField(_('home page'),
  1295. blank=True, verify_exists=False)
  1296. comment = models.TextField(_('comment'))
  1297. pub_date = models.DateTimeField(_('Published date'),
  1298. editable=False, auto_add_now=True)
  1299. is_spam = models.BooleanField(_('spam?'),
  1300. default=False, editable=False)
  1301. class Meta:
  1302. verbose_name = _('comment')
  1303. verbose_name_plural = _('comments')
  1304. In the view where the comment is posted, I first write the comment
  1305. to the database, then I launch the spam filter task in the background.
  1306. .. _task-example-blog-views:
  1307. ``blog/views.py``
  1308. -----------------
  1309. .. code-block:: python
  1310. from django import forms
  1311. from django.http import HttpResponseRedirect
  1312. from django.template.context import RequestContext
  1313. from django.shortcuts import get_object_or_404, render_to_response
  1314. from blog import tasks
  1315. from blog.models import Comment
  1316. class CommentForm(forms.ModelForm):
  1317. class Meta:
  1318. model = Comment
  1319. def add_comment(request, slug, template_name='comments/create.html'):
  1320. post = get_object_or_404(Entry, slug=slug)
  1321. remote_addr = request.META.get('REMOTE_ADDR')
  1322. if request.method == 'post':
  1323. form = CommentForm(request.POST, request.FILES)
  1324. if form.is_valid():
  1325. comment = form.save()
  1326. # Check spam asynchronously.
  1327. tasks.spam_filter.delay(comment_id=comment.id,
  1328. remote_addr=remote_addr)
  1329. return HttpResponseRedirect(post.get_absolute_url())
  1330. else:
  1331. form = CommentForm()
  1332. context = RequestContext(request, {'form': form})
  1333. return render_to_response(template_name, context_instance=context)
  1334. To filter spam in comments I use `Akismet`_, the service
  1335. used to filter spam in comments posted to the free blog platform
  1336. `Wordpress`. `Akismet`_ is free for personal use, but for commercial use you
  1337. need to pay. You have to sign up to their service to get an API key.
  1338. To make API calls to `Akismet`_ I use the `akismet.py`_ library written by
  1339. `Michael Foord`_.
  1340. .. _task-example-blog-tasks:
  1341. ``blog/tasks.py``
  1342. -----------------
  1343. .. code-block:: python
  1344. from celery import Celery
  1345. from akismet import Akismet
  1346. from django.core.exceptions import ImproperlyConfigured
  1347. from django.contrib.sites.models import Site
  1348. from blog.models import Comment
  1349. app = Celery(broker='amqp://')
  1350. @app.task
  1351. def spam_filter(comment_id, remote_addr=None):
  1352. logger = spam_filter.get_logger()
  1353. logger.info('Running spam filter for comment %s', comment_id)
  1354. comment = Comment.objects.get(pk=comment_id)
  1355. current_domain = Site.objects.get_current().domain
  1356. akismet = Akismet(settings.AKISMET_KEY, 'http://{0}'.format(domain))
  1357. if not akismet.verify_key():
  1358. raise ImproperlyConfigured('Invalid AKISMET_KEY')
  1359. is_spam = akismet.comment_check(user_ip=remote_addr,
  1360. comment_content=comment.comment,
  1361. comment_author=comment.name,
  1362. comment_author_email=comment.email_address)
  1363. if is_spam:
  1364. comment.is_spam = True
  1365. comment.save()
  1366. return is_spam
  1367. .. _`Akismet`: http://akismet.com/faq/
  1368. .. _`akismet.py`: http://www.voidspace.org.uk/downloads/akismet.py
  1369. .. _`Michael Foord`: http://www.voidspace.org.uk/
  1370. .. _`exponential backoff`: https://en.wikipedia.org/wiki/Exponential_backoff
  1371. .. _`jitter`: https://en.wikipedia.org/wiki/Jitter