tasks.rst 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. =======
  2. Tasks
  3. =======
  4. A task is a class that encapsulates a function and its execution options.
  5. With a function ``create_user``, that takes two arguments: ``username`` and
  6. ``password``, you can create a task like this:
  7. .. code-block:: python
  8. from celery.task import Task
  9. class CreateUserTask(Task):
  10. def run(self, username, password):
  11. create_user(username, password)
  12. For convenience there is a shortcut decorator that turns any function into
  13. a task, ``celery.decorators.task``:
  14. .. code-block:: python
  15. from celery.decorators import task
  16. from django.contrib.auth import User
  17. @task()
  18. def create_user(username, password):
  19. User.objects.create(username=username, password=password)
  20. Note the parens after ``@task()`` the task decorator takes any execution
  21. 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. Task options
  70. ============
  71. * name
  72. This is the name the task is registered as.
  73. You can set this name manually, or just use the default which is
  74. atomatically generated using the module and class name.
  75. * abstract
  76. Abstract classes are not registered, so they're
  77. only used for making new task types by subclassing.
  78. * max_retries
  79. The maximum number of attempted retries before giving up.
  80. If this is exceeded the :exc`celery.execptions.MaxRetriesExceeded`
  81. exception will be raised. Note that you have to retry manually, it's
  82. not something that happens automatically.
  83. * default_retry_delay
  84. Default time in seconds before a retry of the task should be
  85. executed. Default is a 1 minute delay.
  86. * rate_limit
  87. Set the rate limit for this task type,
  88. if this is ``None`` no rate limit is in effect.
  89. The rate limits can be specified in seconds, minutes or hours
  90. by appending ``"/s"``, ``"/m"`` or "``/h"``". If this is an integer
  91. it is interpreted as seconds. Example: ``"100/m" (hundred tasks a
  92. minute). Default is the ``CELERY_DEFAULT_RATE_LIMIT`` setting (which
  93. is off if not specified).
  94. * ignore_result
  95. Don't store the status and return value. This means you can't
  96. use the :class:`celery.result.AsyncResult` to check if the task is
  97. done, or get its return value. Only use if you need the performance
  98. and is able live without these features. Any exceptions raised will
  99. store the return value/status as usual.
  100. * disable_error_emails
  101. Disable all error e-mails for this task.
  102. * serializer
  103. A string identifying the default serialization
  104. method to use. Defaults to the ``CELERY_TASK_SERIALIZER`` setting.
  105. Can be ``pickle`` ``json``, ``yaml``, or any custom serialization
  106. methods that have been registered with
  107. :mod:`carrot.serialization.registry`.
  108. Please see :doc:`userguide/executing` for more information.
  109. Message and routing options
  110. ---------------------------
  111. * routing_key
  112. Override the global default ``routing_key`` for this task.
  113. * exchange
  114. Override the global default ``exchange`` for this task.
  115. * mandatory
  116. If set, the task message has mandatory routing. By default the task
  117. is silently dropped by the broker if it can't be routed to a queue.
  118. However - If the task is mandatory, an exception will be raised
  119. instead.
  120. * immediate
  121. Request immediate delivery. If the task cannot be routed to a
  122. task worker immediately, an exception will be raised. This is
  123. instead of the default behaviour, where the broker will accept and
  124. queue the task, but with no guarantee that the task will ever
  125. be executed.
  126. * priority
  127. The message priority. A number from ``0`` to ``9``, where ``0`` is the
  128. highest. Note that RabbitMQ doesn't support priorities yet.
  129. Please see :doc:`userguide/executing` for descriptions of these options.
  130. How it works
  131. ============
  132. Here comes the technical details, this part isn't something you need to know,
  133. but you may be interested, so here goes.
  134. All defined tasks are listed in a registry. The registry contains
  135. a list of task names and their task classes. You can investigate this registry
  136. by yourself:
  137. .. code-block:: python
  138. >>> from celery.task import registry
  139. >>> from celery import task
  140. >>> registry.tasks
  141. {'celery.delete_expired_task_meta':
  142. <celery.task.builtins.DeleteExpiredTaskMetaTask object at 0x101d1f510>,
  143. 'celery.execute_remote':
  144. <celery.task.base.ExecuteRemoteTask object at 0x101d17890>,
  145. 'celery.task.rest.RESTProxyTask':
  146. <celery.task.rest.RESTProxyTask object at 0x101d1f410>,
  147. 'celery.task.rest.Task': <celery.task.rest.Task object at 0x101d1f4d0>,
  148. 'celery.map_async':
  149. <celery.task.base.AsynchronousMapTask object at 0x101d17910>,
  150. 'celery.ping': <celery.task.builtins.PingTask object at 0x101d1f550>}
  151. This is the list of tasks built-in to celery. Note that we had to import
  152. ``celery.task`` first for these to show up. This is because the tasks will
  153. only be registered when the module it is defined in is imported.
  154. When using the default loader the loader imports any modules listed in the
  155. ``CELERY_IMPORTS`` setting. If using Django it loads all ``tasks.py`` modules
  156. for the applications listed in ``INSTALLED_APPS``. If you want to do something
  157. special you can create your own loader to do what you want.
  158. The entity responsible for registering your task in the registry is a
  159. metaclass, ``celery.task.base.TaskType``, this is the default metaclass for
  160. ``Task``. If you want to register your task manually you can set the
  161. ``abstract`` attribute:
  162. .. code-block:: python
  163. class MyTask(Task):
  164. abstract = True
  165. This way the task won't be registered, but any task subclassing it will.
  166. So when we send a task, we don't send the function code, we just send the name
  167. of the task, so when the worker receives the message it can just look it up in
  168. the task registry to find the execution code.
  169. This means that your workers must optimally be updated with the same software
  170. as the client, this is a drawback, but the alternative is a technical
  171. challenge that has yet to be solved.