tasks.rst 32 KB

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