tasks.rst 30 KB

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