tasks.rst 39 KB

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