tasks.rst 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056
  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, kand not by a worker.
  38. :logfile: The file the worker logs to. See `Logging`_.
  39. :loglevel: The current loglevel 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 logfile 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. superclass when making new task types by subclassing.
  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-emails is enabled for this task, then
  156. this is a whitelist 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 overriden 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 hostname and pid of the worker executing the task
  186. will be avaiable 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 occured, 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. wich 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 subclassing it will be.
  430. When tasks are sent, we don't send any actual function code, just the name
  431. of the task to execute. When the worker then receives the message it can look
  432. up th ename in its task registry to find the execution code.
  433. This means that your workers should always be updated with the same software
  434. as the client. This is a drawback, but the alternative is a technical
  435. challenge that has yet to be solved.
  436. .. _task-best-practices:
  437. Tips and Best Practices
  438. =======================
  439. .. _task-ignore_results:
  440. Ignore results you don't want
  441. -----------------------------
  442. If you don't care about the results of a task, be sure to set the
  443. :attr:`~celery.task.base.BaseTask.ignore_result` option, as storing results
  444. wastes time and resources.
  445. .. code-block:: python
  446. @celery.task(ignore_result=True)
  447. def mytask(...)
  448. something()
  449. Results can even be disabled globally using the :setting:`CELERY_IGNORE_RESULT`
  450. setting.
  451. .. _task-disable-rate-limits:
  452. Disable rate limits if they're not used
  453. ---------------------------------------
  454. Disabling rate limits altogether is recommended if you don't have
  455. any tasks using them. This is because the rate limit subsystem introduces
  456. quite a lot of complexity.
  457. Set the :setting:`CELERY_DISABLE_RATE_LIMITS` setting to globally disable
  458. rate limits:
  459. .. code-block:: python
  460. CELERY_DISABLE_RATE_LIMITS = True
  461. .. _task-synchronous-subtasks:
  462. Avoid launching synchronous subtasks
  463. ------------------------------------
  464. Having a task wait for the result of another task is really inefficient,
  465. and may even cause a deadlock if the worker pool is exhausted.
  466. Make your design asynchronous instead, for example by using *callbacks*.
  467. **Bad**:
  468. .. code-block:: python
  469. @celery.task()
  470. def update_page_info(url):
  471. page = fetch_page.delay(url).get()
  472. info = parse_page.delay(url, page).get()
  473. store_page_info.delay(url, info)
  474. @celery.task()
  475. def fetch_page(url):
  476. return myhttplib.get(url)
  477. @celery.task()
  478. def parse_page(url, page):
  479. return myparser.parse_document(page)
  480. @celery.task()
  481. def store_page_info(url, info):
  482. return PageInfo.objects.create(url, info)
  483. **Good**:
  484. .. code-block:: python
  485. @celery.task(ignore_result=True)
  486. def update_page_info(url):
  487. # fetch_page -> parse_page -> store_page
  488. fetch_page.delay(url, callback=subtask(parse_page,
  489. callback=subtask(store_page_info)))
  490. @celery.task(ignore_result=True)
  491. def fetch_page(url, callback=None):
  492. page = myhttplib.get(url)
  493. if callback:
  494. # The callback may have been serialized with JSON,
  495. # so best practice is to convert the subtask dict back
  496. # into a subtask object.
  497. subtask(callback).delay(url, page)
  498. @celery.task(ignore_result=True)
  499. def parse_page(url, page, callback=None):
  500. info = myparser.parse_document(page)
  501. if callback:
  502. subtask(callback).delay(url, info)
  503. @celery.task(ignore_result=True)
  504. def store_page_info(url, info):
  505. PageInfo.objects.create(url, info)
  506. We use :class:`~celery.task.sets.subtask` here to safely pass
  507. around the callback task. :class:`~celery.task.sets.subtask` is a
  508. subclass of dict used to wrap the arguments and execution options
  509. for a single task invocation.
  510. .. seealso::
  511. :ref:`sets-subtasks` for more information about subtasks.
  512. .. _task-performance-and-strategies:
  513. Performance and Strategies
  514. ==========================
  515. .. _task-granularity:
  516. Granularity
  517. -----------
  518. The task granularity is the amount of computation needed by each subtask.
  519. In general it is better to split the problem up into many small tasks, than
  520. have a few long running tasks.
  521. With smaller tasks you can process more tasks in parallel and the tasks
  522. won't run long enough to block the worker from processing other waiting tasks.
  523. However, executing a task does have overhead. A message needs to be sent, data
  524. may not be local, etc. So if the tasks are too fine-grained the additional
  525. overhead may not be worth it in the end.
  526. .. seealso::
  527. The book `Art of Concurrency`_ has a whole section dedicated to the topic
  528. of task granularity.
  529. .. _`Art of Concurrency`: http://oreilly.com/catalog/9780596521547
  530. .. _task-data-locality:
  531. Data locality
  532. -------------
  533. The worker processing the task should be as close to the data as
  534. possible. The best would be to have a copy in memory, the worst would be a
  535. full transfer from another continent.
  536. If the data is far away, you could try to run another worker at location, or
  537. if that's not possible - cache often used data, or preload data you know
  538. is going to be used.
  539. The easiest way to share data between workers is to use a distributed cache
  540. system, like `memcached`_.
  541. .. seealso::
  542. The paper `Distributed Computing Economics`_ by Jim Gray is an excellent
  543. introduction to the topic of data locality.
  544. .. _`Distributed Computing Economics`:
  545. http://research.microsoft.com/pubs/70001/tr-2003-24.pdf
  546. .. _`memcached`: http://memcached.org/
  547. .. _task-state:
  548. State
  549. -----
  550. Since celery is a distributed system, you can't know in which process, or
  551. on what machine the task will be executed. You can't even know if the task will
  552. run in a timely manner.
  553. The ancient async sayings tells us that “asserting the world is the
  554. responsibility of the task”. What this means is that the world view may
  555. have changed since the task was requested, so the task is responsible for
  556. making sure the world is how it should be; If you have a task
  557. that reindexes a search engine, and the search engine should only be reindexed
  558. at maximum every 5 minutes, then it must be the tasks responsibility to assert
  559. that, not the callers.
  560. Another gotcha is Django model objects. They shouldn't be passed on as arguments
  561. to tasks. It's almost always better to re-fetch the object from the
  562. database when the task is running instead, as using old data may lead
  563. to race conditions.
  564. Imagine the following scenario where you have an article and a task
  565. that automatically expands some abbreviations in it:
  566. .. code-block:: python
  567. class Article(models.Model):
  568. title = models.CharField()
  569. body = models.TextField()
  570. @celery.task
  571. def expand_abbreviations(article):
  572. article.body.replace("MyCorp", "My Corporation")
  573. article.save()
  574. First, an author creates an article and saves it, then the author
  575. clicks on a button that initiates the abbreviation task.
  576. >>> article = Article.objects.get(id=102)
  577. >>> expand_abbreviations.delay(model_object)
  578. Now, the queue is very busy, so the task won't be run for another 2 minutes.
  579. In the meantime another author makes changes to the article, so
  580. when the task is finally run, the body of the article is reverted to the old
  581. version because the task had the old body in its argument.
  582. Fixing the race condition is easy, just use the article id instead, and
  583. re-fetch the article in the task body:
  584. .. code-block:: python
  585. @celery.task
  586. def expand_abbreviations(article_id):
  587. article = Article.objects.get(id=article_id)
  588. article.body.replace("MyCorp", "My Corporation")
  589. article.save()
  590. >>> expand_abbreviations(article_id)
  591. There might even be performance benefits to this approach, as sending large
  592. messages may be expensive.
  593. .. _task-database-transactions:
  594. Database transactions
  595. ---------------------
  596. Let's have a look at another example:
  597. .. code-block:: python
  598. from django.db import transaction
  599. @transaction.commit_on_success
  600. def create_article(request):
  601. article = Article.objects.create(....)
  602. expand_abbreviations.delay(article.pk)
  603. This is a Django view creating an article object in the database,
  604. then passing the primary key to a task. It uses the `commit_on_success`
  605. decorator, which will commit the transaction when the view returns, or
  606. roll back if the view raises an exception.
  607. There is a race condition if the task starts executing
  608. before the transaction has been committed; The database object does not exist
  609. yet!
  610. The solution is to *always commit transactions before sending tasks
  611. depending on state from the current transaction*:
  612. .. code-block:: python
  613. @transaction.commit_manually
  614. def create_article(request):
  615. try:
  616. article = Article.objects.create(...)
  617. except:
  618. transaction.rollback()
  619. raise
  620. else:
  621. transaction.commit()
  622. expand_abbreviations.delay(article.pk)
  623. .. _task-example:
  624. Example
  625. =======
  626. Let's take a real wold example; A blog where comments posted needs to be
  627. filtered for spam. When the comment is created, the spam filter runs in the
  628. background, so the user doesn't have to wait for it to finish.
  629. We have a Django blog application allowing comments
  630. on blog posts. We'll describe parts of the models/views and tasks for this
  631. application.
  632. blog/models.py
  633. --------------
  634. The comment model looks like this:
  635. .. code-block:: python
  636. from django.db import models
  637. from django.utils.translation import ugettext_lazy as _
  638. class Comment(models.Model):
  639. name = models.CharField(_("name"), max_length=64)
  640. email_address = models.EmailField(_("e-mail address"))
  641. homepage = models.URLField(_("home page"),
  642. blank=True, verify_exists=False)
  643. comment = models.TextField(_("comment"))
  644. pub_date = models.DateTimeField(_("Published date"),
  645. editable=False, auto_add_now=True)
  646. is_spam = models.BooleanField(_("spam?"),
  647. default=False, editable=False)
  648. class Meta:
  649. verbose_name = _("comment")
  650. verbose_name_plural = _("comments")
  651. In the view where the comment is posted, we first write the comment
  652. to the database, then we launch the spam filter task in the background.
  653. .. _task-example-blog-views:
  654. blog/views.py
  655. -------------
  656. .. code-block:: python
  657. from django import forms
  658. from django.http import HttpResponseRedirect
  659. from django.template.context import RequestContext
  660. from django.shortcuts import get_object_or_404, render_to_response
  661. from blog import tasks
  662. from blog.models import Comment
  663. class CommentForm(forms.ModelForm):
  664. class Meta:
  665. model = Comment
  666. def add_comment(request, slug, template_name="comments/create.html"):
  667. post = get_object_or_404(Entry, slug=slug)
  668. remote_addr = request.META.get("REMOTE_ADDR")
  669. if request.method == "post":
  670. form = CommentForm(request.POST, request.FILES)
  671. if form.is_valid():
  672. comment = form.save()
  673. # Check spam asynchronously.
  674. tasks.spam_filter.delay(comment_id=comment.id,
  675. remote_addr=remote_addr)
  676. return HttpResponseRedirect(post.get_absolute_url())
  677. else:
  678. form = CommentForm()
  679. context = RequestContext(request, {"form": form})
  680. return render_to_response(template_name, context_instance=context)
  681. To filter spam in comments we use `Akismet`_, the service
  682. used to filter spam in comments posted to the free weblog platform
  683. `Wordpress`. `Akismet`_ is free for personal use, but for commercial use you
  684. need to pay. You have to sign up to their service to get an API key.
  685. To make API calls to `Akismet`_ we use the `akismet.py`_ library written by
  686. `Michael Foord`_.
  687. .. _task-example-blog-tasks:
  688. blog/tasks.py
  689. -------------
  690. .. code-block:: python
  691. from akismet import Akismet
  692. from celery.decorators import task
  693. from django.core.exceptions import ImproperlyConfigured
  694. from django.contrib.sites.models import Site
  695. from blog.models import Comment
  696. @task
  697. def spam_filter(comment_id, remote_addr=None):
  698. logger = spam_filter.get_logger()
  699. logger.info("Running spam filter for comment %s" % comment_id)
  700. comment = Comment.objects.get(pk=comment_id)
  701. current_domain = Site.objects.get_current().domain
  702. akismet = Akismet(settings.AKISMET_KEY, "http://%s" % domain)
  703. if not akismet.verify_key():
  704. raise ImproperlyConfigured("Invalid AKISMET_KEY")
  705. is_spam = akismet.comment_check(user_ip=remote_addr,
  706. comment_content=comment.comment,
  707. comment_author=comment.name,
  708. comment_author_email=comment.email_address)
  709. if is_spam:
  710. comment.is_spam = True
  711. comment.save()
  712. return is_spam
  713. .. _`Akismet`: http://akismet.com/faq/
  714. .. _`akismet.py`: http://www.voidspace.org.uk/downloads/akismet.py
  715. .. _`Michael Foord`: http://www.voidspace.org.uk/