tasks.rst 38 KB

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