tasks.rst 37 KB

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