tasks.rst 20 KB

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