executing.rst 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. .. _guide-executing:
  2. =================
  3. Executing Tasks
  4. =================
  5. .. contents::
  6. :local:
  7. .. _executing-basics:
  8. Basics
  9. ======
  10. Executing tasks is done with :meth:`~celery.task.Base.Task.apply_async`,
  11. and the shortcut: :meth:`~celery.task.Base.Task.delay`.
  12. ``delay`` is simple and convenient, as it looks like calling a regular
  13. function:
  14. .. code-block:: python
  15. Task.delay(arg1, arg2, kwarg1="x", kwarg2="y")
  16. The same using ``apply_async`` is written like this:
  17. .. code-block:: python
  18. Task.apply_async(args=[arg1, arg2], kwargs={"kwarg1": "x", "kwarg2": "y"})
  19. While ``delay`` is convenient, it doesn't give you as much control as using
  20. ``apply_async``. With ``apply_async`` you can override the execution options
  21. available as attributes on the ``Task`` class (see :ref:`task-options`).
  22. In addition you can set countdown/eta, task expiry, provide a custom broker
  23. connection and more.
  24. Let's go over these in more detail. All the examples uses a simple task,
  25. called ``add``, taking two positional arguments and returning the sum:
  26. .. code-block:: python
  27. @task
  28. def add(x, y):
  29. return x + y
  30. .. note::
  31. You can also execute a task by name using
  32. :func:`~celery.execute.send_task`, if you don't have access to the
  33. task class::
  34. >>> from celery.execute import send_task
  35. >>> result = send_task("tasks.add", [2, 2])
  36. >>> result.get()
  37. 4
  38. .. _executing-eta:
  39. ETA and countdown
  40. =================
  41. The ETA (estimated time of arrival) lets you set a specific date and time that
  42. is the earliest time at which your task will be executed. ``countdown`` is
  43. a shortcut to set eta by seconds into the future.
  44. .. code-block:: python
  45. >>> result = add.apply_async(args=[10, 10], countdown=3)
  46. >>> result.get() # this takes at least 3 seconds to return
  47. 20
  48. The task is guaranteed to be executed at some time *after* the
  49. specified date and time, but not necessarily at that exact time.
  50. Possible reasons for broken deadlines may include many items waiting
  51. in the queue, or heavy network latency. To make sure your tasks
  52. are executed in a timely manner you should monitor queue lenghts. Use
  53. Munin, or similar tools, to receive alerts, so appropiate action can be
  54. taken to ease the workload. See :ref:`monitoring-munin`.
  55. While ``countdown`` is an integer, ``eta`` must be a :class:`~datetime.datetime`
  56. object, specifying an exact date and time (including millisecond precision,
  57. and timezone information):
  58. .. code-block:: python
  59. >>> from datetime import datetime, timedelta
  60. >>> tomorrow = datetime.now() + timedelta(days=1)
  61. >>> add.apply_async(args=[10, 10], eta=tomorrow)
  62. .. _executing-expiration:
  63. Expiration
  64. ==========
  65. The ``expires`` argument defines an optional expiry time,
  66. either as seconds after task publish, or a specific date and time using
  67. :class:~datetime.datetime`:
  68. .. code-block:: python
  69. >>> # Task expires after one minute from now.
  70. >>> add.apply_async(args=[10, 10], expires=60)
  71. >>> # Also supports datetime
  72. >>> from datetime import datetime, timedelta
  73. >>> add.apply_async(args=[10, 10], kwargs,
  74. ... expires=datetime.now() + timedelta(days=1)
  75. When a worker receives an expired task it will mark
  76. the task as :state:`REVOKED` (:exc:`~celery.exceptions.TaskRevokedError`).
  77. .. _executing-serializers:
  78. Serializers
  79. ===========
  80. Data transferred between clients and workers needs to be serialized.
  81. The default serializer is :mod:`pickle`, but you can
  82. change this globally or for each individual task.
  83. There is built-in support for :mod:`pickle`, ``JSON``, ``YAML``
  84. and ``msgpack``, and you can also add your own custom serializers by registering
  85. them into the Carrot serializer registry (see
  86. `Kombu: Serialization of Data`_).
  87. .. _`Kombu: Serialization of Data`:
  88. http://packages.python.org/kombu/introduction.html#serialization-of-data
  89. Each option has its advantages and disadvantages.
  90. json -- JSON is supported in many programming languages, is now
  91. a standard part of Python (since 2.6), and is fairly fast to decode
  92. using the modern Python libraries such as :mod:`cjson` or :mod:`simplejson`.
  93. The primary disadvantage to JSON is that it limits you to the following
  94. data types: strings, unicode, floats, boolean, dictionaries, and lists.
  95. Decimals and dates are notably missing.
  96. Also, binary data will be transferred using base64 encoding, which will
  97. cause the transferred data to be around 34% larger than an encoding which
  98. supports native binary types.
  99. However, if your data fits inside the above constraints and you need
  100. cross-language support, the default setting of JSON is probably your
  101. best choice.
  102. See http://json.org for more information.
  103. pickle -- If you have no desire to support any language other than
  104. Python, then using the pickle encoding will gain you the support of
  105. all built-in Python data types (except class instances), smaller
  106. messages when sending binary files, and a slight speedup over JSON
  107. processing.
  108. See http://docs.python.org/library/pickle.html for more information.
  109. yaml -- YAML has many of the same characteristics as json,
  110. except that it natively supports more data types (including dates,
  111. recursive references, etc.)
  112. However, the Python libraries for YAML are a good bit slower than the
  113. libraries for JSON.
  114. If you need a more expressive set of data types and need to maintain
  115. cross-language compatibility, then YAML may be a better fit than the above.
  116. See http://yaml.org/ for more information.
  117. msgpack -- msgpack is a binary serialization format that is closer to JSON
  118. in features. It is very young however, and support should be considered
  119. experimental at this point.
  120. See http://msgpack.org/ for more information.
  121. The encoding used is available as a message header, so the worker knows how to
  122. deserialize any task. If you use a custom serializer, this serializer must
  123. be available for the worker.
  124. The client uses the following order to decide which serializer
  125. to use when sending a task:
  126. 1. The ``serializer`` argument to ``apply_async``
  127. 2. The tasks ``serializer`` attribute
  128. 3. The default :setting:`CELERY_TASK_SERIALIZER` setting.
  129. *Using the ``serializer`` argument to ``apply_async``*:
  130. .. code-block:: python
  131. >>> add.apply_async(args=[10, 10], serializer="json")
  132. .. _executing-connections:
  133. Connections and connection timeouts.
  134. ====================================
  135. Currently there is no support for broker connection pools, so
  136. ``apply_async`` establishes and closes a new connection every time
  137. it is called. This is something you need to be aware of when sending
  138. more than one task at a time.
  139. You handle the connection manually by creating a
  140. publisher:
  141. .. code-block:: python
  142. numbers = [(2, 2), (4, 4), (8, 8), (16, 16)]
  143. results = []
  144. publisher = add.get_publisher()
  145. try:
  146. for args in numbers:
  147. res = add.apply_async(args=args, publisher=publisher)
  148. results.append(res)
  149. finally:
  150. publisher.close()
  151. publisher.connection.close()
  152. print([res.get() for res in results])
  153. .. note::
  154. This particularly example is better expressed as a task set.
  155. See :ref:`sets-taskset`. Tasksets already reuses connections.
  156. The connection timeout is the number of seconds to wait before giving up
  157. on establishing the connection. You can set this by using the
  158. ``connect_timeout`` argument to ``apply_async``:
  159. .. code-block:: python
  160. add.apply_async([10, 10], connect_timeout=3)
  161. Or if you handle the connection manually:
  162. .. code-block:: python
  163. publisher = add.get_publisher(connect_timeout=3)
  164. .. _executing-routing:
  165. Routing options
  166. ===============
  167. Celery uses the AMQP routing mechanisms to route tasks to different workers.
  168. Messages (tasks) are sent to exchanges, a queue binds to an exchange with a
  169. routing key. Let's look at an example:
  170. Let's pretend we have an application with lot of different tasks: some
  171. process video, others process images, and some gather collective intelligence
  172. about its users. Some of these tasks are more important, so we want to make
  173. sure the high priority tasks get sent to dedicated nodes.
  174. For the sake of this example we have a single exchange called ``tasks``.
  175. There are different types of exchanges, each type interpreting the routing
  176. key in different ways, implementing different messaging scenarios.
  177. The most common types used with Celery are ``direct`` and ``topic``.
  178. * direct
  179. Matches the routing key exactly.
  180. * topic
  181. In the topic exchange the routing key is made up of words separated by
  182. dots (``.``). Words can be matched by the wild cards ``*`` and ``#``,
  183. where ``*`` matches one exact word, and ``#`` matches one or many words.
  184. For example, ``*.stock.#`` matches the routing keys ``usd.stock`` and
  185. ``euro.stock.db`` but not ``stock.nasdaq``.
  186. We create three queues, ``video``, ``image`` and ``lowpri`` that binds to
  187. the ``tasks`` exchange. For the queues we use the following binding keys::
  188. video: video.#
  189. image: image.#
  190. lowpri: misc.#
  191. Now we can send our tasks to different worker machines, by making the workers
  192. listen to different queues:
  193. .. code-block:: python
  194. >>> add.apply_async(args=[filename],
  195. ... routing_key="video.compress")
  196. >>> add.apply_async(args=[filename, 360],
  197. ... routing_key="image.rotate")
  198. >>> add.apply_async(args=[filename, selection],
  199. ... routing_key="image.crop")
  200. >>> add.apply_async(routing_key="misc.recommend")
  201. Later, if the crop task is consuming a lot of resources,
  202. we can bind new workers to handle just the ``"image.crop"`` task,
  203. by creating a new queue that binds to ``"image.crop``".
  204. .. seealso::
  205. To find out more about routing, please see :ref:`guide-routing`.
  206. .. _executing-amq-opts:
  207. AMQP options
  208. ============
  209. * mandatory
  210. This sets the delivery to be mandatory. An exception will be raised
  211. if there are no running workers able to take on the task.
  212. Not supported by :mod:`amqplib`.
  213. * immediate
  214. Request immediate delivery. Will raise an exception
  215. if the task cannot be routed to a worker immediately.
  216. Not supported by :mod:`amqplib`.
  217. * priority
  218. A number between ``0`` and ``9``, where ``0`` is the highest priority.
  219. .. note::
  220. RabbitMQ does not yet support AMQP priorities.