tasks.rst 37 KB

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