tasks.rst 39 KB

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