tasks.rst 37 KB

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