tasks.rst 22 KB

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