tasks.rst 40 KB

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