tasks.rst 37 KB

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