executing.rst 8.0 KB

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