tasks.rst 36 KB

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