tasks.rst 39 KB

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