tasks.rst 54 KB

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