executing.rst 7.7 KB

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