tasks.rst 38 KB

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