tasks.rst 16 KB

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