tasks.rst 37 KB

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