tasks.rst 32 KB

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