tasks.rst 39 KB

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