tasks.rst 41 KB

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