executing.rst 7.5 KB

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