tasks.rst 38 KB

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