executing.rst 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  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 its 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 thing using ``apply_async`` is written like this:
  17. .. code-block:: python
  18. Task.apply_async(args=[arg1, arg2], kwargs={"kwarg1": "x", "kwarg2": "y"})
  19. You can also execute a task by name using :func:`~celery.execute.send_task`,
  20. if you don't have access to the task's class::
  21. >>> from celery.execute import send_task
  22. >>> result = send_task("tasks.add", [2, 2])
  23. >>> result.get()
  24. 4
  25. While ``delay`` is convenient, it doesn't give you as much control as using ``apply_async``.
  26. With ``apply_async`` you can override the execution options available as attributes on
  27. the ``Task`` class: ``routing_key``, ``exchange``, ``immediate``, ``mandatory``,
  28. ``priority``, and ``serializer``. In addition you can set a countdown/eta, or provide
  29. a custom broker connection.
  30. Let's go over these in more detail. The following examples use this simple
  31. task, which adds together two numbers:
  32. .. code-block:: python
  33. @task
  34. def add(x, y):
  35. return x + y
  36. .. _executing-eta:
  37. ETA and countdown
  38. =================
  39. The ETA (estimated time of arrival) lets you set a specific date and time that
  40. is the earliest time at which your task will execute. ``countdown`` is
  41. a shortcut to set this by seconds in the future.
  42. .. code-block:: python
  43. >>> result = add.apply_async(args=[10, 10], countdown=3)
  44. >>> result.get() # this takes at least 3 seconds to return
  45. 20
  46. Note that your task is guaranteed to be executed at some time *after* the
  47. specified date and time has passed, but not necessarily at that exact time.
  48. While ``countdown`` is an integer, ``eta`` must be a :class:`~datetime.datetime` object,
  49. specifying an exact date and time in the future. This is good if you already
  50. have a :class:`~datetime.datetime` object and need to modify it with a
  51. :class:`~datetime.timedelta`, or when using time in seconds is not very readable.
  52. .. code-block:: python
  53. from datetime import datetime, timedelta
  54. def add_tomorrow(username):
  55. """Add this tomorrow."""
  56. tomorrow = datetime.now() + timedelta(days=1)
  57. add.apply_async(args=[10, 10], eta=tomorrow)
  58. .. _executing-serializers:
  59. Serializers
  60. ===========
  61. Data passed between celery and workers has to be serialized to be
  62. transferred. The default serializer is :mod:`pickle`, but you can
  63. change this for each
  64. task. There is built-in support for using :mod:`pickle`, ``JSON`` and ``YAML``,
  65. and you can add your own custom serializers by registering them into the
  66. carrot serializer registry.
  67. The default serializer (pickle) supports Python objects, like ``datetime`` and
  68. any custom datatypes you define yourself. But since pickle has poor support
  69. outside of the Python language, you need to choose another serializer if you
  70. need to communicate with other languages. In that case, ``JSON`` is a very
  71. popular choice.
  72. The serialization method is sent with the message, so the worker knows how to
  73. deserialize any task. Of course, if you use a custom serializer, this must
  74. also be registered in the worker.
  75. When sending a task the serialization method is taken from the following
  76. places in order: The ``serializer`` argument to ``apply_async``, the
  77. Task's ``serializer`` attribute, and finally the global default ``CELERY_SERIALIZER``
  78. configuration directive.
  79. .. code-block:: python
  80. >>> add.apply_async(args=[10, 10], serializer="json")
  81. .. _executing-connections:
  82. Connections and connection timeouts.
  83. ====================================
  84. Currently there is no support for broker connection pools in celery,
  85. so this is something you need to be aware of when sending more than
  86. one task at a time, as ``apply_async``/``delay`` establishes and
  87. closes a connection every time.
  88. If you need to send more than one task at the same time, it's a good idea to
  89. establish the connection yourself and pass it to ``apply_async``:
  90. .. code-block:: python
  91. numbers = [(2, 2), (4, 4), (8, 8), (16, 16)]
  92. results = []
  93. publisher = add.get_publisher()
  94. try:
  95. for args in numbers:
  96. res = add.apply_async(args=args, publisher=publisher)
  97. results.append(res)
  98. finally:
  99. publisher.close()
  100. publisher.connection.close()
  101. print([res.get() for res in results])
  102. The connection timeout is the number of seconds to wait before we give up
  103. establishing the connection. You can set this with the ``connect_timeout``
  104. argument to ``apply_async``:
  105. .. code-block:: python
  106. add.apply_async([10, 10], connect_timeout=3)
  107. Or if you handle the connection manually:
  108. .. code-block:: python
  109. publisher = add.get_publisher(connect_timeout=3)
  110. .. _executing-routing:
  111. Routing options
  112. ===============
  113. Celery uses the AMQP routing mechanisms to route tasks to different workers.
  114. You can route tasks using the following entities: exchange, queue and routing key.
  115. Messages (tasks) are sent to exchanges, a queue binds to an exchange with a
  116. routing key. Let's look at an example:
  117. Our application has a lot of tasks, some process video, others process images,
  118. and some gather collective intelligence about users. Some of these have
  119. higher priority than others so we want to make sure the high priority tasks
  120. get sent to powerful machines, while low priority tasks are sent to dedicated
  121. machines that can handle these at their own pace.
  122. For the sake of example we have only one exchange called ``tasks``.
  123. There are different types of exchanges that matches the routing key in
  124. different ways, the exchange types are:
  125. * direct
  126. Matches the routing key exactly.
  127. * topic
  128. In the topic exchange the routing key is made up of words separated by dots (``.``).
  129. Words can be matched by the wild cards ``*`` and ``#``, where ``*`` matches one
  130. exact word, and ``#`` matches one or many.
  131. For example, ``*.stock.#`` matches the routing keys ``usd.stock`` and
  132. ``euro.stock.db`` but not ``stock.nasdaq``.
  133. (there are also other exchange types, but these are not used by celery)
  134. So, we create three queues, ``video``, ``image`` and ``lowpri`` that bind to
  135. our ``tasks`` exchange. For the queues we use the following binding keys::
  136. video: video.#
  137. image: image.#
  138. lowpri: misc.#
  139. Now we can send our tasks to different worker machines, by making the workers
  140. listen to different queues:
  141. .. code-block:: python
  142. >>> add.apply_async(args=[filename],
  143. ... routing_key="video.compress")
  144. >>> add.apply_async(args=[filename, 360],
  145. ... routing_key="image.rotate")
  146. >>> add.apply_async(args=[filename, selection],
  147. ... routing_key="image.crop")
  148. >>> add.apply_async(routing_key="misc.recommend")
  149. Later, if the crop task is consuming a lot of resources,
  150. we can bind some new workers to handle just the ``"image.crop"`` task,
  151. by creating a new queue that binds to ``"image.crop``".
  152. To find out more about routing, please see :ref:`guide-routing`.
  153. .. _executing-amq-opts:
  154. AMQP options
  155. ============
  156. **NOTE** The ``mandatory`` and ``immediate`` flags are not supported by
  157. ``amqplib`` at this point.
  158. * mandatory
  159. This sets the delivery to be mandatory. An exception will be raised
  160. if there are no running workers able to take on the task.
  161. * immediate
  162. Request immediate delivery. Will raise an exception
  163. if the task cannot be routed to a worker immediately.
  164. * priority
  165. A number between ``0`` and ``9``, where ``0`` is the highest priority.
  166. Note that RabbitMQ does not implement AMQP priorities, and maybe your broker
  167. does not either, consult your broker's documentation for more
  168. information.