tasks.rst 17 KB

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