tasks.rst 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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. How it works
  167. ============
  168. Here comes the technical details, this part isn't something you need to know,
  169. but you may be interested, so here goes.
  170. All defined tasks are listed in a registry. The registry contains
  171. a list of task names and their task classes. You can investigate this registry
  172. by yourself:
  173. .. code-block:: python
  174. >>> from celery.task import registry
  175. >>> from celery import task
  176. >>> registry.tasks
  177. {'celery.delete_expired_task_meta':
  178. <celery.task.builtins.DeleteExpiredTaskMetaTask object at 0x101d1f510>,
  179. 'celery.execute_remote':
  180. <celery.task.base.ExecuteRemoteTask object at 0x101d17890>,
  181. 'celery.task.rest.RESTProxyTask':
  182. <celery.task.rest.RESTProxyTask object at 0x101d1f410>,
  183. 'celery.task.rest.Task': <celery.task.rest.Task object at 0x101d1f4d0>,
  184. 'celery.map_async':
  185. <celery.task.base.AsynchronousMapTask object at 0x101d17910>,
  186. 'celery.ping': <celery.task.builtins.PingTask object at 0x101d1f550>}
  187. This is the list of tasks built-in to celery. Note that we had to import
  188. ``celery.task`` first for these to show up. This is because the tasks will
  189. only be registered when the module it is defined in is imported.
  190. When using the default loader the loader imports any modules listed in the
  191. ``CELERY_IMPORTS`` setting. If using Django it loads all ``tasks.py`` modules
  192. for the applications listed in ``INSTALLED_APPS``. If you want to do something
  193. special you can create your own loader to do what you want.
  194. The entity responsible for registering your task in the registry is a
  195. meta class, :class:`TaskType`, this is the default meta class for
  196. ``Task``. If you want to register your task manually you can set the
  197. ``abstract`` attribute:
  198. .. code-block:: python
  199. class MyTask(Task):
  200. abstract = True
  201. This way the task won't be registered, but any task sub classing it will.
  202. So when we send a task, we don't send the function code, we just send the name
  203. of the task, so when the worker receives the message it can just look it up in
  204. the task registry to find the execution code.
  205. This means that your workers must optimally be updated with the same software
  206. as the client, this is a drawback, but the alternative is a technical
  207. challenge that has yet to be solved.
  208. Performance and Strategies
  209. ==========================
  210. Granularity
  211. -----------
  212. The tasks granularity is the degree of parallelization your task have.
  213. It's better to have a lot of small tasks, than just a few long running
  214. ones.
  215. With smaller tasks, you can process more tasks in parallel and the tasks
  216. won't run long enough to block the worker from processing other waiting tasks.
  217. But there's a limit, sending messages takes processing power and bandwidth. If
  218. your tasks are so short the overhead of passing them around is worse than
  219. just executing them in-line, you should reconsider your strategy. There is no
  220. universal answer here.
  221. Data locality
  222. -------------
  223. The worker processing the task should optimally be as close to the data as
  224. possible. The best would be to have a copy in memory, the worst being a
  225. full transfer from another continent.
  226. If the data is far away, you could try to run another worker at location, or
  227. if that's not possible, cache often used data, or preload data you know
  228. is going to be used.
  229. The easiest way to share data between workers is to use a distributed caching
  230. system, like `memcached`_.
  231. For more information about data-locality, please read
  232. http://research.microsoft.com/pubs/70001/tr-2003-24.pdf
  233. .. _`memcached`: http://memcached.org/
  234. State
  235. -----
  236. Since celery is a distributed system, you can't know in which process, or even
  237. on what machine the task will run, also you can't even know if the task will
  238. run in a timely manner, so please be wary of the state you pass on to tasks.
  239. One gotcha is Django model objects, they shouldn't be passed on as arguments
  240. to task classes, it's almost always better to re-fetch the object from the
  241. database instead, as there are possible race conditions involved.
  242. Imagine the following scenario where you have an article, and a task
  243. that automatically expands some abbreviations in it.
  244. .. code-block:: python
  245. class Article(models.Model):
  246. title = models.CharField()
  247. body = models.TextField()
  248. @task
  249. def expand_abbreviations(article):
  250. article.body.replace("MyCorp", "My Corporation")
  251. article.save()
  252. First, an author creates an article and saves it, then the author
  253. clicks on a button that initiates the abbreviation task.
  254. >>> article = Article.objects.get(id=102)
  255. >>> expand_abbreviations.delay(model_object)
  256. Now, the queue is very busy, so the task won't be run for another 2 minutes,
  257. in the meantime another author makes some changes to the article,
  258. when the task is finally run, the body of the article is reverted to the old
  259. version, because the task had the old body in its argument.
  260. Fixing the race condition is easy, just use the article id instead, and
  261. re-fetch the article in the task body:
  262. .. code-block:: python
  263. @task
  264. def expand_abbreviations(article_id)
  265. article = Article.objects.get(id=article_id)
  266. article.body.replace("MyCorp", "My Corporation")
  267. article.save()
  268. >>> expand_abbreviations(article_id)
  269. There might even be performance benefits to this approach, as sending large
  270. messages may be expensive.