tasks.rst 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  1. =======
  2. Tasks
  3. =======
  4. .. module:: celery.task.base
  5. A task is a class that encapsulates a function and its execution options.
  6. Given a function ``create_user``, that takes two arguments: ``username`` and
  7. ``password``, you can create a task like this:
  8. .. code-block:: python
  9. from celery.task import Task
  10. class CreateUserTask(Task):
  11. def run(self, username, password):
  12. create_user(username, password)
  13. For convenience there is a shortcut decorator that turns any function into
  14. a task, :func:`celery.decorators.task`:
  15. .. code-block:: python
  16. from celery.decorators import task
  17. from django.contrib.auth import User
  18. @task
  19. def create_user(username, password):
  20. User.objects.create(username=username, password=password)
  21. The task decorator takes the same execution options as the
  22. :class:`~celery.task.base.Task` class does:
  23. .. code-block:: python
  24. @task(serializer="json")
  25. def create_user(username, password):
  26. User.objects.create(username=username, password=password)
  27. An alternative way to use the decorator is to give the function as an argument
  28. instead, but if you do this be sure to set the resulting tasks :attr:`__name__`
  29. attribute, so pickle is able to find it in reverse:
  30. .. code-block:: python
  31. create_user_task = task()(create_user)
  32. create_user_task.__name__ = "create_user_task"
  33. Default keyword arguments
  34. =========================
  35. Celery supports a set of default arguments that can be forwarded to any task.
  36. Tasks can choose not to take these, or list the ones they want.
  37. The worker will do the right thing.
  38. The current default keyword arguments are:
  39. * logfile
  40. The log file, can be passed on to
  41. :meth:`~celery.task.base.Task.get_logger` to gain access to
  42. the workers log file. See `Logging`_.
  43. * loglevel
  44. The loglevel used.
  45. * task_id
  46. The unique id of the executing task.
  47. * task_name
  48. Name of the executing task.
  49. * task_retries
  50. How many times the current task has been retried.
  51. An integer starting at ``0``.
  52. * task_is_eager
  53. Set to :const:`True` if the task is executed locally in the client,
  54. and not by a worker.
  55. * delivery_info
  56. Additional message delivery information. This is a mapping containing
  57. the exchange and routing key used to deliver this task. It's used
  58. by e.g. :meth:`~celery.task.base.Task.retry` to resend the task to the
  59. same destination queue.
  60. **NOTE** As some messaging backends doesn't have advanced routing
  61. capabilities, you can't trust the availability of keys in this mapping.
  62. Logging
  63. =======
  64. You can use the workers logger to add diagnostic output to
  65. the worker log:
  66. .. code-block:: python
  67. class AddTask(Task):
  68. def run(self, x, y, **kwargs):
  69. logger = self.get_logger(**kwargs)
  70. logger.info("Adding %s + %s" % (x, y))
  71. return x + y
  72. or using the decorator syntax:
  73. .. code-block:: python
  74. @task()
  75. def add(x, y, **kwargs):
  76. logger = add.get_logger(**kwargs)
  77. logger.info("Adding %s + %s" % (x, y))
  78. return x + y
  79. There are several logging levels available, and the workers ``loglevel``
  80. setting decides whether or not they will be written to the log file.
  81. Retrying a task if something fails
  82. ==================================
  83. Simply use :meth:`~celery.task.base.Task.retry` to re-send the task.
  84. It will do the right thing, and respect the
  85. :attr:`~celery.task.base.Task.max_retries` attribute:
  86. .. code-block:: python
  87. @task()
  88. def send_twitter_status(oauth, tweet, **kwargs):
  89. try:
  90. twitter = Twitter(oauth)
  91. twitter.update_status(tweet)
  92. except (Twitter.FailWhaleError, Twitter.LoginError), exc:
  93. send_twitter_status.retry(args=[oauth, tweet], kwargs=kwargs, exc=exc)
  94. Here we used the ``exc`` argument to pass the current exception to
  95. :meth:`Task.retry`. At each step of the retry this exception
  96. is available as the tombstone (result) of the task. When
  97. :attr:`Task.max_retries` has been exceeded this is the exception
  98. raised. However, if an ``exc`` argument is not provided the
  99. :exc:`RetryTaskError` exception is raised instead.
  100. **Important note:** The task has to take the magic keyword arguments
  101. in order for max retries to work properly, this is because it keeps track
  102. of the current number of retries using the ``task_retries`` keyword argument
  103. passed on to the task. In addition, it also uses the ``task_id`` keyword
  104. argument to use the same task id, and ``delivery_info`` to route the
  105. retried task to the same destination.
  106. Using a custom retry delay
  107. --------------------------
  108. When a task is to be retried, it will wait for a given amount of time
  109. before doing so. The default delay is in the :attr:`Task.default_retry_delay`
  110. attribute on the task. By default this is set to 3 minutes. Note that the
  111. unit for setting the delay is in seconds (int or float).
  112. You can also provide the ``countdown`` argument to
  113. :meth:`~celery.task.base.Task.retry` to override this default.
  114. .. code-block:: python
  115. class MyTask(Task):
  116. default_retry_delay = 30 * 60 # retry in 30 minutes
  117. def run(self, x, y, **kwargs):
  118. try:
  119. ...
  120. except Exception, exc:
  121. self.retry([x, y], kwargs, exc=exc,
  122. countdown=60) # override the default and
  123. # - retry in 1 minute
  124. Task options
  125. ============
  126. * name
  127. The name the task is registered as.
  128. You can set this name manually, or just use the default which is
  129. automatically generated using the module and class name.
  130. * abstract
  131. Abstract classes are not registered, but are used as the superclass
  132. when making new task types by subclassing.
  133. * max_retries
  134. The maximum number of attempted retries before giving up.
  135. If this is exceeded the :exc`~celery.execptions.MaxRetriesExceeded`
  136. exception will be raised. Note that you have to retry manually, it's
  137. not something that happens automatically.
  138. * default_retry_delay
  139. Default time in seconds before a retry of the task should be
  140. executed. Can be either an ``int`` or a ``float``.
  141. Default is a 1 minute delay (``60 seconds``).
  142. * rate_limit
  143. Set the rate limit for this task type, that is, how many times in a given
  144. period of time is the task allowed to run.
  145. If this is ``None`` no rate limit is in effect.
  146. If it is an integer, it is interpreted as "tasks per second".
  147. The rate limits can be specified in seconds, minutes or hours
  148. by appending ``"/s"``, ``"/m"`` or "``/h"``" to the value.
  149. Example: ``"100/m" (hundred tasks a
  150. minute). Default is the ``CELERY_DEFAULT_RATE_LIMIT`` setting, which if not
  151. specified means rate limiting for tasks is turned off by default.
  152. * ignore_result
  153. Don't store the status and return value. This means you can't
  154. use the :class:`celery.result.AsyncResult` to check if the task is
  155. done, or get its return value. Only use if you need the performance
  156. and is able live without these features. Any exceptions raised will
  157. store the return value/status as usual.
  158. * disable_error_emails
  159. Disable error e-mails for this task. Default is ``False``.
  160. *Note:* You can also turn off error e-mails globally using the
  161. ``CELERY_SEND_TASK_ERROR_EMAILS`` setting.
  162. * serializer
  163. A string identifying the default serialization
  164. method to use. Defaults to the ``CELERY_TASK_SERIALIZER`` setting.
  165. Can be ``pickle`` ``json``, ``yaml``, or any custom serialization
  166. methods that have been registered with
  167. :mod:`carrot.serialization.registry`.
  168. Please see :doc:`executing` for more information.
  169. Message and routing options
  170. ---------------------------
  171. * routing_key
  172. Override the global default ``routing_key`` for this task.
  173. * exchange
  174. Override the global default ``exchange`` for this task.
  175. * mandatory
  176. If set, the task message has mandatory routing. By default the task
  177. is silently dropped by the broker if it can't be routed to a queue.
  178. However - If the task is mandatory, an exception will be raised
  179. instead.
  180. * immediate
  181. Request immediate delivery. If the task cannot be routed to a
  182. task worker immediately, an exception will be raised. This is
  183. instead of the default behavior, where the broker will accept and
  184. queue the task, but with no guarantee that the task will ever
  185. be executed.
  186. * priority
  187. The message priority. A number from ``0`` to ``9``, where ``0`` is the
  188. highest. **Note:** RabbitMQ does not support priorities yet.
  189. See :doc:`executing` for more information about the messaging options
  190. available.
  191. Example
  192. =======
  193. Let's take a real wold example; A blog where comments posted needs to be
  194. filtered for spam. When the comment is created, the spam filter runs in the
  195. background, so the user doesn't have to wait for it to finish.
  196. We have a Django blog application allowing comments
  197. on blog posts. We'll describe parts of the models/views and tasks for this
  198. application.
  199. blog/models.py
  200. --------------
  201. The comment model looks like this:
  202. .. code-block:: python
  203. from django.db import models
  204. from django.utils.translation import ugettext_lazy as _
  205. class Comment(models.Model):
  206. name = models.CharField(_("name"), max_length=64)
  207. email_address = models.EmailField(_("e-mail address"))
  208. homepage = models.URLField(_("home page"),
  209. blank=True, verify_exists=False)
  210. comment = models.TextField(_("comment"))
  211. pub_date = models.DateTimeField(_("Published date"),
  212. editable=False, auto_add_now=True)
  213. is_spam = models.BooleanField(_("spam?"),
  214. default=False, editable=False)
  215. class Meta:
  216. verbose_name = _("comment")
  217. verbose_name_plural = _("comments")
  218. In the view where the comment is posted, we first write the comment
  219. to the database, then we launch the spam filter task in the background.
  220. blog/views.py
  221. -------------
  222. .. code-block:: python
  223. from django import forms
  224. frmo django.http import HttpResponseRedirect
  225. from django.template.context import RequestContext
  226. from django.shortcuts import get_object_or_404, render_to_response
  227. from blog import tasks
  228. from blog.models import Comment
  229. class CommentForm(forms.ModelForm):
  230. class Meta:
  231. model = Comment
  232. def add_comment(request, slug, template_name="comments/create.html"):
  233. post = get_object_or_404(Entry, slug=slug)
  234. remote_addr = request.META.get("REMOTE_ADDR")
  235. if request.method == "post":
  236. form = CommentForm(request.POST, request.FILES)
  237. if form.is_valid():
  238. comment = form.save()
  239. # Check spam asynchronously.
  240. tasks.spam_filter.delay(comment_id=comment.id,
  241. remote_addr=remote_addr)
  242. return HttpResponseRedirect(post.get_absolute_url())
  243. else:
  244. form = CommentForm()
  245. context = RequestContext(request, {"form": form})
  246. return render_to_response(template_name, context_instance=context)
  247. To filter spam in comments we use `Akismet`_, the service
  248. used to filter spam in comments posted to the free weblog platform
  249. `Wordpress`. `Akismet`_ is free for personal use, but for commercial use you
  250. need to pay. You have to sign up to their service to get an API key.
  251. To make API calls to `Akismet`_ we use the `akismet.py`_ library written by
  252. Michael Foord.
  253. blog/tasks.py
  254. -------------
  255. .. code-block:: python
  256. from akismet import Akismet
  257. from celery.decorators import task
  258. from django.core.exceptions import ImproperlyConfigured
  259. from django.contrib.sites.models import Site
  260. from blog.models import Comment
  261. @task
  262. def spam_filter(comment_id, remote_addr=None, **kwargs):
  263. logger = spam_filter.get_logger(**kwargs)
  264. logger.info("Running spam filter for comment %s" % comment_id)
  265. comment = Comment.objects.get(pk=comment_id)
  266. current_domain = Site.objects.get_current().domain
  267. akismet = Akismet(settings.AKISMET_KEY, "http://%s" % domain)
  268. if not akismet.verify_key():
  269. raise ImproperlyConfigured("Invalid AKISMET_KEY")
  270. is_spam = akismet.comment_check(user_ip=remote_addr,
  271. comment_content=comment.comment,
  272. comment_author=comment.name,
  273. comment_author_email=comment.email_address)
  274. if is_spam:
  275. comment.is_spam = True
  276. comment.save()
  277. return is_spam
  278. .. _`Akismet`: http://akismet.com/faq/
  279. .. _`akismet.py`: http://www.voidspace.org.uk/downloads/akismet.py
  280. How it works
  281. ============
  282. Here comes the technical details, this part isn't something you need to know,
  283. but you may be interested.
  284. All defined tasks are listed in a registry. The registry contains
  285. a list of task names and their task classes. You can investigate this registry
  286. yourself:
  287. .. code-block:: python
  288. >>> from celery import registry
  289. >>> from celery import task
  290. >>> registry.tasks
  291. {'celery.delete_expired_task_meta':
  292. <PeriodicTask: celery.delete_expired_task_meta (periodic)>,
  293. 'celery.task.http.HttpDispatchTask':
  294. <Task: celery.task.http.HttpDispatchTask (regular)>,
  295. 'celery.execute_remote':
  296. <Task: celery.execute_remote (regular)>,
  297. 'celery.map_async':
  298. <Task: celery.map_async (regular)>,
  299. 'celery.ping':
  300. <Task: celery.ping (regular)>}
  301. This is the list of tasks built-in to celery. Note that we had to import
  302. ``celery.task`` first for these to show up. This is because the tasks will
  303. only be registered when the module they are defined in is imported.
  304. The default loader imports any modules listed in the
  305. ``CELERY_IMPORTS`` setting.
  306. The entity responsible for registering your task in the registry is a
  307. meta class, :class:`~celery.task.base.TaskType`. This is the default
  308. meta class for :class:`~celery.task.base.Task`. If you want to register
  309. your task manually you can set the :attr:`~celery.task.base.Task.abstract`
  310. attribute:
  311. .. code-block:: python
  312. class MyTask(Task):
  313. abstract = True
  314. This way the task won't be registered, but any task subclassing it will.
  315. When tasks are sent, we don't send the function code, just the name
  316. of the task. When the worker receives the message it can just look it up in
  317. the task registry to find the execution code.
  318. This means that your workers should always be updated with the same software
  319. as the client. This is a drawback, but the alternative is a technical
  320. challenge that has yet to be solved.
  321. Tips and Best Practices
  322. =======================
  323. Ignore results you don't want
  324. -----------------------------
  325. If you don't care about the results of a task, be sure to set the
  326. :attr:`~celery.task.base.Task.ignore_result` option, as storing results
  327. wastes time and resources.
  328. .. code-block:: python
  329. @task(ignore_result=True)
  330. def mytask(...)
  331. something()
  332. Results can even be disabled globally using the ``CELERY_IGNORE_RESULT``
  333. setting.
  334. Disable rate limits if they're not used
  335. ---------------------------------------
  336. Disabling rate limits altogether is recommended if you don't have
  337. any tasks using them. This is because the rate limit subsystem introduces
  338. quite a lot of complexity.
  339. Set the ``CELERY_DISABLE_RATE_LIMITS`` setting to globally disable
  340. rate limits:
  341. .. code-block:: python
  342. CELERY_DISABLE_RATE_LIMITS = True
  343. Avoid launching synchronous subtasks
  344. ------------------------------------
  345. Having a task wait for the result of another task is really inefficient,
  346. and may even cause a deadlock if the worker pool is exhausted.
  347. Make your design asynchronous instead, for example by using *callbacks*.
  348. Bad:
  349. .. code-block:: python
  350. @task()
  351. def update_page_info(url):
  352. page = fetch_page.delay(url).get()
  353. info = parse_page.delay(url, page).get()
  354. store_page_info.delay(url, info)
  355. @task()
  356. def fetch_page(url):
  357. return myhttplib.get(url)
  358. @task()
  359. def parse_page(url, page):
  360. return myparser.parse_document(page)
  361. @task()
  362. def store_page_info(url, info):
  363. return PageInfo.objects.create(url, info)
  364. Good:
  365. .. code-block:: python
  366. from functools import curry
  367. @task(ignore_result=True)
  368. def update_page_info(url):
  369. # fetch_page -> parse_page -> store_page
  370. callback = curry(parse_page.delay, callback=store_page_info)
  371. fetch_page.delay(url, callback=callback)
  372. @task(ignore_result=True)
  373. def fetch_page(url, callback=None):
  374. page = myparser.parse_document(page)
  375. if callback:
  376. callback(page)
  377. @task(ignore_result=True)
  378. def parse_page(url, page, callback=None):
  379. info = myparser.parse_document(page)
  380. if callback:
  381. callback(url, info)
  382. @task(ignore_result=True)
  383. def store_page_info(url, info):
  384. PageInfo.objects.create(url, info)
  385. Performance and Strategies
  386. ==========================
  387. Granularity
  388. -----------
  389. The task's granularity is the degree of parallelization your task have.
  390. It's better to have many small tasks, than a few long running ones.
  391. With smaller tasks, you can process more tasks in parallel and the tasks
  392. won't run long enough to block the worker from processing other waiting tasks.
  393. However, there's a limit. Sending messages takes processing power and bandwidth. If
  394. your tasks are so short the overhead of passing them around is worse than
  395. just executing them in-line, you should reconsider your strategy. There is no
  396. universal answer here.
  397. Data locality
  398. -------------
  399. The worker processing the task should be as close to the data as
  400. possible. The best would be to have a copy in memory, the worst being a
  401. full transfer from another continent.
  402. If the data is far away, you could try to run another worker at location, or
  403. if that's not possible, cache often used data, or preload data you know
  404. is going to be used.
  405. The easiest way to share data between workers is to use a distributed caching
  406. system, like `memcached`_.
  407. For more information about data-locality, please read
  408. http://research.microsoft.com/pubs/70001/tr-2003-24.pdf
  409. .. _`memcached`: http://memcached.org/
  410. State
  411. -----
  412. Since celery is a distributed system, you can't know in which process, or even
  413. on what machine the task will run. Indeed you can't even know if the task will
  414. run in a timely manner, so please be wary of the state you pass on to tasks.
  415. One gotcha is Django model objects. They shouldn't be passed on as arguments
  416. to task classes, it's almost always better to re-fetch the object from the
  417. database instead, as there are possible race conditions involved.
  418. Imagine the following scenario where you have an article and a task
  419. that automatically expands some abbreviations in it.
  420. .. code-block:: python
  421. class Article(models.Model):
  422. title = models.CharField()
  423. body = models.TextField()
  424. @task
  425. def expand_abbreviations(article):
  426. article.body.replace("MyCorp", "My Corporation")
  427. article.save()
  428. First, an author creates an article and saves it, then the author
  429. clicks on a button that initiates the abbreviation task.
  430. >>> article = Article.objects.get(id=102)
  431. >>> expand_abbreviations.delay(model_object)
  432. Now, the queue is very busy, so the task won't be run for another 2 minutes,
  433. in the meantime another author makes some changes to the article,
  434. when the task is finally run, the body of the article is reverted to the old
  435. version, because the task had the old body in its argument.
  436. Fixing the race condition is easy, just use the article id instead, and
  437. re-fetch the article in the task body:
  438. .. code-block:: python
  439. @task
  440. def expand_abbreviations(article_id)
  441. article = Article.objects.get(id=article_id)
  442. article.body.replace("MyCorp", "My Corporation")
  443. article.save()
  444. >>> expand_abbreviations(article_id)
  445. There might even be performance benefits to this approach, as sending large
  446. messages may be expensive.