executing.rst 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. .. _guide-executing:
  2. =================
  3. Executing Tasks
  4. =================
  5. .. contents::
  6. :local:
  7. .. _executing-basics:
  8. Basics
  9. ======
  10. Executing a task 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`, returning the sum of two positional arguments:
  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 lengths. Use
  53. Munin, or similar tools, to receive alerts, so appropriate 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 Kombu serializer registry (see `Kombu: Serialization of Data`_).
  86. .. _`Kombu: Serialization of Data`:
  87. http://packages.python.org/kombu/introduction.html#serialization-of-data
  88. Each option has its advantages and disadvantages.
  89. json -- JSON is supported in many programming languages, is now
  90. a standard part of Python (since 2.6), and is fairly fast to decode
  91. using the modern Python libraries such as :mod:`cjson` or :mod:`simplejson`.
  92. The primary disadvantage to JSON is that it limits you to the following
  93. data types: strings, Unicode, floats, boolean, dictionaries, and lists.
  94. Decimals and dates are notably missing.
  95. Also, binary data will be transferred using Base64 encoding, which will
  96. cause the transferred data to be around 34% larger than an encoding which
  97. supports native binary types.
  98. However, if your data fits inside the above constraints and you need
  99. cross-language support, the default setting of JSON is probably your
  100. best choice.
  101. See http://json.org for more information.
  102. pickle -- If you have no desire to support any language other than
  103. Python, then using the pickle encoding will gain you the support of
  104. all built-in Python data types (except class instances), smaller
  105. messages when sending binary files, and a slight speedup over JSON
  106. processing.
  107. See http://docs.python.org/library/pickle.html for more information.
  108. yaml -- YAML has many of the same characteristics as json,
  109. except that it natively supports more data types (including dates,
  110. recursive references, etc.)
  111. However, the Python libraries for YAML are a good bit slower than the
  112. libraries for JSON.
  113. If you need a more expressive set of data types and need to maintain
  114. cross-language compatibility, then YAML may be a better fit than the above.
  115. See http://yaml.org/ for more information.
  116. msgpack -- msgpack is a binary serialization format that is closer to JSON
  117. in features. It is very young however, and support should be considered
  118. experimental at this point.
  119. See http://msgpack.org/ for more information.
  120. The encoding used is available as a message header, so the worker knows how to
  121. deserialize any task. If you use a custom serializer, this serializer must
  122. be available for the worker.
  123. The client uses the following order to decide which serializer
  124. to use when sending a task:
  125. 1. The `serializer` argument to `apply_async`
  126. 2. The tasks `serializer` attribute
  127. 3. The default :setting:`CELERY_TASK_SERIALIZER` setting.
  128. * Using the `serializer` argument to `apply_async`:
  129. .. code-block:: python
  130. >>> add.apply_async(args=[10, 10], serializer="json")
  131. .. _executing-connections:
  132. Connections and connection timeouts.
  133. ====================================
  134. Currently there is no support for broker connection pools, so
  135. `apply_async` establishes and closes a new connection every time
  136. it is called. This is something you need to be aware of when sending
  137. more than one task at a time.
  138. You handle the connection manually by creating a
  139. publisher:
  140. .. code-block:: python
  141. numbers = [(2, 2), (4, 4), (8, 8), (16, 16)]
  142. results = []
  143. publisher = add.get_publisher()
  144. try:
  145. for args in numbers:
  146. res = add.apply_async(args=args, publisher=publisher)
  147. results.append(res)
  148. finally:
  149. publisher.close()
  150. publisher.connection.close()
  151. print([res.get() for res in results])
  152. .. note::
  153. This particular example is better expressed as a task set.
  154. See :ref:`sets-taskset`. Tasksets already reuses connections.
  155. The connection timeout is the number of seconds to wait before giving up
  156. on establishing the connection. You can set this by using the
  157. `connect_timeout` argument to `apply_async`:
  158. .. code-block:: python
  159. add.apply_async([10, 10], connect_timeout=3)
  160. Or if you handle the connection manually:
  161. .. code-block:: python
  162. publisher = add.get_publisher(connect_timeout=3)
  163. .. _executing-routing:
  164. Routing options
  165. ===============
  166. Celery uses the AMQP routing mechanisms to route tasks to different workers.
  167. Messages (tasks) are sent to exchanges, a queue binds to an exchange with a
  168. routing key. Let's look at an example:
  169. Let's pretend we have an application with lot of different tasks: some
  170. process video, others process images, and some gather collective intelligence
  171. about its users. Some of these tasks are more important, so we want to make
  172. sure the high priority tasks get sent to dedicated nodes.
  173. For the sake of this example we have a single exchange called `tasks`.
  174. There are different types of exchanges, each type interpreting the routing
  175. key in different ways, implementing different messaging scenarios.
  176. The most common types used with Celery are `direct` and `topic`.
  177. * direct
  178. Matches the routing key exactly.
  179. * topic
  180. In the topic exchange the routing key is made up of words separated by
  181. dots (`.`). Words can be matched by the wild cards `*` and `#`,
  182. where `*` matches one exact word, and `#` matches one or many words.
  183. For example, `*.stock.#` matches the routing keys `usd.stock` and
  184. `euro.stock.db` but not `stock.nasdaq`.
  185. We create three queues, `video`, `image` and `lowpri` that binds to
  186. the `tasks` exchange. For the queues we use the following binding keys::
  187. video: video.#
  188. image: image.#
  189. lowpri: misc.#
  190. Now we can send our tasks to different worker machines, by making the workers
  191. listen to different queues:
  192. .. code-block:: python
  193. >>> add.apply_async(args=[filename],
  194. ... routing_key="video.compress")
  195. >>> add.apply_async(args=[filename, 360],
  196. ... routing_key="image.rotate")
  197. >>> add.apply_async(args=[filename, selection],
  198. ... routing_key="image.crop")
  199. >>> add.apply_async(routing_key="misc.recommend")
  200. Later, if the crop task is consuming a lot of resources,
  201. we can bind new workers to handle just the `"image.crop"` task,
  202. by creating a new queue that binds to `"image.crop`".
  203. .. seealso::
  204. To find out more about routing, please see :ref:`guide-routing`.
  205. .. _executing-amq-opts:
  206. AMQP options
  207. ============
  208. * mandatory
  209. This sets the delivery to be mandatory. An exception will be raised
  210. if there are no running workers able to take on the task.
  211. Not supported by :mod:`amqplib`.
  212. * immediate
  213. Request immediate delivery. Will raise an exception
  214. if the task cannot be routed to a worker immediately.
  215. Not supported by :mod:`amqplib`.
  216. * priority
  217. A number between `0` and `9`, where `0` is the highest priority.
  218. .. note::
  219. RabbitMQ does not yet support AMQP priorities.