tasks.rst 40 KB

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