tasks.rst 38 KB

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