tasks.rst 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655
  1. =======
  2. Tasks
  3. =======
  4. .. module:: celery.task.base
  5. .. contents::
  6. :local:
  7. Basics
  8. ======
  9. A task is a class that encapsulates a function and its execution options.
  10. Given a function ``create_user``, that takes two arguments: ``username`` and
  11. ``password``, you can create a task like this:
  12. .. code-block:: python
  13. from celery.task import Task
  14. class CreateUserTask(Task):
  15. def run(self, username, password):
  16. create_user(username, password)
  17. For convenience there is a shortcut decorator that turns any function into
  18. a task, :func:`celery.decorators.task`:
  19. .. code-block:: python
  20. from celery.decorators import task
  21. from django.contrib.auth import User
  22. @task
  23. def create_user(username, password):
  24. User.objects.create(username=username, password=password)
  25. The task decorator takes the same execution options as the
  26. :class:`~celery.task.base.Task` class does:
  27. .. code-block:: python
  28. @task(serializer="json")
  29. def create_user(username, password):
  30. User.objects.create(username=username, password=password)
  31. Default keyword arguments
  32. =========================
  33. Celery supports a set of default arguments that can be forwarded to any task.
  34. Tasks can choose not to take these, or list the ones they want.
  35. The worker will do the right thing.
  36. The current default keyword arguments are:
  37. * logfile
  38. The log file, can be passed on to
  39. :meth:`~celery.task.base.Task.get_logger` to gain access to
  40. 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. * task_is_eager
  51. Set to :const:`True` if the task is executed locally in the client,
  52. and not by a worker.
  53. * delivery_info
  54. Additional message delivery information. This is a mapping containing
  55. the exchange and routing key used to deliver this task. It's used
  56. by e.g. :meth:`~celery.task.base.Task.retry` to resend the task to the
  57. same destination queue.
  58. **NOTE** As some messaging backends doesn't have advanced routing
  59. capabilities, you can't trust the availability of keys in this mapping.
  60. Logging
  61. =======
  62. You can use the workers logger to add diagnostic output to
  63. the worker log:
  64. .. code-block:: python
  65. class AddTask(Task):
  66. def run(self, x, y, **kwargs):
  67. logger = self.get_logger(**kwargs)
  68. logger.info("Adding %s + %s" % (x, y))
  69. return x + y
  70. or using the decorator syntax:
  71. .. code-block:: python
  72. @task()
  73. def add(x, y, **kwargs):
  74. logger = add.get_logger(**kwargs)
  75. logger.info("Adding %s + %s" % (x, y))
  76. return x + y
  77. There are several logging levels available, and the workers ``loglevel``
  78. setting decides whether or not they will be written to the log file.
  79. Of course, you can also simply use ``print`` as anything written to standard
  80. out/-err will be written to the logfile as well.
  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. * queue
  172. Use the routing settings from a queue defined in ``CELERY_QUEUES``.
  173. If defined the ``exchange`` and ``routing_key`` options will be ignored.
  174. * exchange
  175. Override the global default ``exchange`` for this task.
  176. * routing_key
  177. Override the global default ``routing_key`` for this task.
  178. * mandatory
  179. If set, the task message has mandatory routing. By default the task
  180. is silently dropped by the broker if it can't be routed to a queue.
  181. However - If the task is mandatory, an exception will be raised
  182. instead.
  183. * immediate
  184. Request immediate delivery. If the task cannot be routed to a
  185. task worker immediately, an exception will be raised. This is
  186. instead of the default behavior, where the broker will accept and
  187. queue the task, but with no guarantee that the task will ever
  188. be executed.
  189. * priority
  190. The message priority. A number from ``0`` to ``9``, where ``0`` is the
  191. highest. **Note:** RabbitMQ does not support priorities yet.
  192. See :doc:`executing` for more information about the messaging options
  193. available, also :doc:`routing`.
  194. Example
  195. =======
  196. Let's take a real wold example; A blog where comments posted needs to be
  197. filtered for spam. When the comment is created, the spam filter runs in the
  198. background, so the user doesn't have to wait for it to finish.
  199. We have a Django blog application allowing comments
  200. on blog posts. We'll describe parts of the models/views and tasks for this
  201. application.
  202. blog/models.py
  203. --------------
  204. The comment model looks like this:
  205. .. code-block:: python
  206. from django.db import models
  207. from django.utils.translation import ugettext_lazy as _
  208. class Comment(models.Model):
  209. name = models.CharField(_("name"), max_length=64)
  210. email_address = models.EmailField(_("e-mail address"))
  211. homepage = models.URLField(_("home page"),
  212. blank=True, verify_exists=False)
  213. comment = models.TextField(_("comment"))
  214. pub_date = models.DateTimeField(_("Published date"),
  215. editable=False, auto_add_now=True)
  216. is_spam = models.BooleanField(_("spam?"),
  217. default=False, editable=False)
  218. class Meta:
  219. verbose_name = _("comment")
  220. verbose_name_plural = _("comments")
  221. In the view where the comment is posted, we first write the comment
  222. to the database, then we launch the spam filter task in the background.
  223. blog/views.py
  224. -------------
  225. .. code-block:: python
  226. from django import forms
  227. frmo django.http import HttpResponseRedirect
  228. from django.template.context import RequestContext
  229. from django.shortcuts import get_object_or_404, render_to_response
  230. from blog import tasks
  231. from blog.models import Comment
  232. class CommentForm(forms.ModelForm):
  233. class Meta:
  234. model = Comment
  235. def add_comment(request, slug, template_name="comments/create.html"):
  236. post = get_object_or_404(Entry, slug=slug)
  237. remote_addr = request.META.get("REMOTE_ADDR")
  238. if request.method == "post":
  239. form = CommentForm(request.POST, request.FILES)
  240. if form.is_valid():
  241. comment = form.save()
  242. # Check spam asynchronously.
  243. tasks.spam_filter.delay(comment_id=comment.id,
  244. remote_addr=remote_addr)
  245. return HttpResponseRedirect(post.get_absolute_url())
  246. else:
  247. form = CommentForm()
  248. context = RequestContext(request, {"form": form})
  249. return render_to_response(template_name, context_instance=context)
  250. To filter spam in comments we use `Akismet`_, the service
  251. used to filter spam in comments posted to the free weblog platform
  252. `Wordpress`. `Akismet`_ is free for personal use, but for commercial use you
  253. need to pay. You have to sign up to their service to get an API key.
  254. To make API calls to `Akismet`_ we use the `akismet.py`_ library written by
  255. Michael Foord.
  256. blog/tasks.py
  257. -------------
  258. .. code-block:: python
  259. from akismet import Akismet
  260. from celery.decorators import task
  261. from django.core.exceptions import ImproperlyConfigured
  262. from django.contrib.sites.models import Site
  263. from blog.models import Comment
  264. @task
  265. def spam_filter(comment_id, remote_addr=None, **kwargs):
  266. logger = spam_filter.get_logger(**kwargs)
  267. logger.info("Running spam filter for comment %s" % comment_id)
  268. comment = Comment.objects.get(pk=comment_id)
  269. current_domain = Site.objects.get_current().domain
  270. akismet = Akismet(settings.AKISMET_KEY, "http://%s" % domain)
  271. if not akismet.verify_key():
  272. raise ImproperlyConfigured("Invalid AKISMET_KEY")
  273. is_spam = akismet.comment_check(user_ip=remote_addr,
  274. comment_content=comment.comment,
  275. comment_author=comment.name,
  276. comment_author_email=comment.email_address)
  277. if is_spam:
  278. comment.is_spam = True
  279. comment.save()
  280. return is_spam
  281. .. _`Akismet`: http://akismet.com/faq/
  282. .. _`akismet.py`: http://www.voidspace.org.uk/downloads/akismet.py
  283. How it works
  284. ============
  285. Here comes the technical details, this part isn't something you need to know,
  286. but you may be interested.
  287. All defined tasks are listed in a registry. The registry contains
  288. a list of task names and their task classes. You can investigate this registry
  289. yourself:
  290. .. code-block:: python
  291. >>> from celery import registry
  292. >>> from celery import task
  293. >>> registry.tasks
  294. {'celery.delete_expired_task_meta':
  295. <PeriodicTask: celery.delete_expired_task_meta (periodic)>,
  296. 'celery.task.http.HttpDispatchTask':
  297. <Task: celery.task.http.HttpDispatchTask (regular)>,
  298. 'celery.execute_remote':
  299. <Task: celery.execute_remote (regular)>,
  300. 'celery.map_async':
  301. <Task: celery.map_async (regular)>,
  302. 'celery.ping':
  303. <Task: celery.ping (regular)>}
  304. This is the list of tasks built-in to celery. Note that we had to import
  305. ``celery.task`` first for these to show up. This is because the tasks will
  306. only be registered when the module they are defined in is imported.
  307. The default loader imports any modules listed in the
  308. ``CELERY_IMPORTS`` setting.
  309. The entity responsible for registering your task in the registry is a
  310. meta class, :class:`~celery.task.base.TaskType`. This is the default
  311. meta class for :class:`~celery.task.base.Task`. If you want to register
  312. your task manually you can set the :attr:`~celery.task.base.Task.abstract`
  313. attribute:
  314. .. code-block:: python
  315. class MyTask(Task):
  316. abstract = True
  317. This way the task won't be registered, but any task subclassing it will.
  318. When tasks are sent, we don't send the function code, just the name
  319. of the task. When the worker receives the message it can just look it up in
  320. the task registry to find the execution code.
  321. This means that your workers should always be updated with the same software
  322. as the client. This is a drawback, but the alternative is a technical
  323. challenge that has yet to be solved.
  324. Tips and Best Practices
  325. =======================
  326. Ignore results you don't want
  327. -----------------------------
  328. If you don't care about the results of a task, be sure to set the
  329. :attr:`~celery.task.base.Task.ignore_result` option, as storing results
  330. wastes time and resources.
  331. .. code-block:: python
  332. @task(ignore_result=True)
  333. def mytask(...)
  334. something()
  335. Results can even be disabled globally using the ``CELERY_IGNORE_RESULT``
  336. setting.
  337. Disable rate limits if they're not used
  338. ---------------------------------------
  339. Disabling rate limits altogether is recommended if you don't have
  340. any tasks using them. This is because the rate limit subsystem introduces
  341. quite a lot of complexity.
  342. Set the ``CELERY_DISABLE_RATE_LIMITS`` setting to globally disable
  343. rate limits:
  344. .. code-block:: python
  345. CELERY_DISABLE_RATE_LIMITS = True
  346. Avoid launching synchronous subtasks
  347. ------------------------------------
  348. Having a task wait for the result of another task is really inefficient,
  349. and may even cause a deadlock if the worker pool is exhausted.
  350. Make your design asynchronous instead, for example by using *callbacks*.
  351. Bad:
  352. .. code-block:: python
  353. @task()
  354. def update_page_info(url):
  355. page = fetch_page.delay(url).get()
  356. info = parse_page.delay(url, page).get()
  357. store_page_info.delay(url, info)
  358. @task()
  359. def fetch_page(url):
  360. return myhttplib.get(url)
  361. @task()
  362. def parse_page(url, page):
  363. return myparser.parse_document(page)
  364. @task()
  365. def store_page_info(url, info):
  366. return PageInfo.objects.create(url, info)
  367. Good:
  368. .. code-block:: python
  369. @task(ignore_result=True)
  370. def update_page_info(url):
  371. # fetch_page -> parse_page -> store_page
  372. fetch_page.delay(url, callback=subtask(parse_page,
  373. callback=subtask(store_page_info)))
  374. @task(ignore_result=True)
  375. def fetch_page(url, callback=None):
  376. page = myparser.parse_document(page)
  377. if callback:
  378. # The callback may have been serialized with JSON,
  379. # so best practice is to convert the subtask dict back
  380. # into a subtask object.
  381. subtask(callback).delay(page)
  382. @task(ignore_result=True)
  383. def parse_page(url, page, callback=None):
  384. info = myparser.parse_document(page)
  385. if callback:
  386. subtask(callback).delay(url, info)
  387. @task(ignore_result=True)
  388. def store_page_info(url, info):
  389. PageInfo.objects.create(url, info)
  390. We use :class:`~celery.task.sets.subtask` here to safely pass
  391. around the callback task. :class:`~celery.task.sets.subtask` is a
  392. subclass of dict used to wrap the arguments and execution options
  393. for a single task invocation. See :doc:`tasksets` for more information about
  394. subtasks.
  395. Performance and Strategies
  396. ==========================
  397. Granularity
  398. -----------
  399. The task's granularity is the degree of parallelization your task have.
  400. It's better to have many small tasks, than a few long running ones.
  401. With smaller tasks, you can process more tasks in parallel and the tasks
  402. won't run long enough to block the worker from processing other waiting tasks.
  403. However, there's a limit. Sending messages takes processing power and bandwidth. If
  404. your tasks are so short the overhead of passing them around is worse than
  405. just executing them in-line, you should reconsider your strategy. There is no
  406. universal answer here.
  407. Data locality
  408. -------------
  409. The worker processing the task should be as close to the data as
  410. possible. The best would be to have a copy in memory, the worst being a
  411. full transfer from another continent.
  412. If the data is far away, you could try to run another worker at location, or
  413. if that's not possible, cache often used data, or preload data you know
  414. is going to be used.
  415. The easiest way to share data between workers is to use a distributed caching
  416. system, like `memcached`_.
  417. For more information about data-locality, please read
  418. http://research.microsoft.com/pubs/70001/tr-2003-24.pdf
  419. .. _`memcached`: http://memcached.org/
  420. State
  421. -----
  422. Since celery is a distributed system, you can't know in which process, or even
  423. on what machine the task will run. Indeed you can't even know if the task will
  424. run in a timely manner, so please be wary of the state you pass on to tasks.
  425. One gotcha is Django model objects. They shouldn't be passed on as arguments
  426. to task classes, it's almost always better to re-fetch the object from the
  427. database instead, as there are possible race conditions involved.
  428. Imagine the following scenario where you have an article and a task
  429. that automatically expands some abbreviations in it.
  430. .. code-block:: python
  431. class Article(models.Model):
  432. title = models.CharField()
  433. body = models.TextField()
  434. @task
  435. def expand_abbreviations(article):
  436. article.body.replace("MyCorp", "My Corporation")
  437. article.save()
  438. First, an author creates an article and saves it, then the author
  439. clicks on a button that initiates the abbreviation task.
  440. >>> article = Article.objects.get(id=102)
  441. >>> expand_abbreviations.delay(model_object)
  442. Now, the queue is very busy, so the task won't be run for another 2 minutes,
  443. in the meantime another author makes some changes to the article,
  444. when the task is finally run, the body of the article is reverted to the old
  445. version, because the task had the old body in its argument.
  446. Fixing the race condition is easy, just use the article id instead, and
  447. re-fetch the article in the task body:
  448. .. code-block:: python
  449. @task
  450. def expand_abbreviations(article_id)
  451. article = Article.objects.get(id=article_id)
  452. article.body.replace("MyCorp", "My Corporation")
  453. article.save()
  454. >>> expand_abbreviations(article_id)
  455. There might even be performance benefits to this approach, as sending large
  456. messages may be expensive.