executing.rst 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. =================
  2. Executing Tasks
  3. =================
  4. Executing tasks is done with ``apply_async``, and it's 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 uses this simple
  18. task, used to add 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 for
  26. when after, your task should execute. ``countdown`` is a shortcut to set this
  27. by seconds into 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. Serializer
  46. ----------
  47. The default serializer used is :mod:`pickle`, but you can change this for each
  48. task. There is built-in support for using ``pickle``, ``JSON`` and ``YAML``,
  49. and you can add your own custom serializers by registering them into the
  50. carrot serializer registry.
  51. The serialization method is sent with the message, so the worker knows how to
  52. deserialize any task. Of course, if you use a custom serializer, this must
  53. also be registered in the worker.
  54. When sending a task the serialization method is taken from the following
  55. places in order: The ``serializer`` argument to ``apply_async``, the
  56. Task's ``serializer`` attribute, and finally the global default ``CELERY_SERIALIZER``
  57. configuration directive.
  58. .. code-block:: python
  59. >>> add.apply_async(args=[10, 10], serializer="json")
  60. Connections and connection timeouts.
  61. ------------------------------------
  62. Currently there is no support for broker connection pools in celery,
  63. so this is something you need to be aware of when sending more than
  64. one task at a time, as ``apply_async``/``delay`` establishes and
  65. closes a connection every time.
  66. If you need to send more than one task at the same time, it's a good idea to
  67. establish the connection yourself and pass it to ``apply_async``:
  68. .. code-block:: python
  69. from celery.messaging import establish_connection
  70. numbers = [(2, 2), (4, 4), (8, 8), (16, 16)]
  71. results = []
  72. connection = establish_connection()
  73. try:
  74. for args in numbers:
  75. res = add.apply_async(args=args, connection=connection)
  76. results.append(res)
  77. finally:
  78. connection.close()
  79. print([res.get() for res in results])
  80. In Python 2.5 and above, you can use the ``with`` statement:
  81. .. code-block:: python
  82. from __future__ import with_statement
  83. from celery.messaging import establish_connection
  84. numbers = [(2, 2), (4, 4), (8, 8), (16, 16)]
  85. results = []
  86. with establish_connection() as connection:
  87. for args in numbers:
  88. res = add.apply_async(args=args, connection=connection)
  89. results.append(res)
  90. print([res.get() for res in results])
  91. The connection timeout is the number of seconds to wait before we give up
  92. establishing the connection, you can set this with the ``connect_timeout``
  93. argument to ``apply_async``:
  94. .. code-block:: python
  95. add.apply_async([10, 10], connect_timeout=3)
  96. or if you handle the connection manually:
  97. .. code-block:: python
  98. connection = establish_connection(connect_timeout=3)
  99. Routing options
  100. ---------------
  101. Celery uses the AMQP routing mechanisms to route tasks to different workers.
  102. You can route tasks using the following entities: exchange, queue and routing key.
  103. Messages (tasks) are sent to exchanges, a queue binds to an exchange with a
  104. routing key. Let's look at an example:
  105. Our application has a lot of tasks, some process video, others process images,
  106. and some gathers collective intelligence about users. Some of these have
  107. higher priority than others so we want to make sure the high priority tasks
  108. get sent to powerful machines, while low priority tasks are sent to dedicated
  109. machines that can handle these at their own pace, uninterrupted.
  110. For the sake of example we have only one exchange called ``tasks``.
  111. There are different types of exchanges that matches the routing key in
  112. different ways, the exchange types are:
  113. * direct
  114. Matches the routing key exactly.
  115. * topic
  116. In the topic exchange the routing key is made up of words separated by dots (``.``).
  117. Words can be matched by the wild cards ``*`` and ``#``, where ``*`` matches one
  118. exact word, and ``#`` matches one or many.
  119. For example, ``*.stock.#`` matches the routing keys ``usd.stock`` and
  120. ``euro.stock.db`` but not ``stock.nasdaq``.
  121. (there are also other exchange types, but these are not used by celery)
  122. So, we create three queues, ``video``, ``image`` and ``lowpri`` that binds to
  123. our ``tasks`` exchange, for the queues we use the following binding keys::
  124. video: video.#
  125. image: image.#
  126. lowpri: misc.#
  127. Now we can send our tasks to different worker machines, by making the workers
  128. listen to different queues:
  129. .. code-block:: python
  130. >>> CompressVideoTask.apply_async(args=[filename],
  131. ... routing_key="video.compress")
  132. >>> ImageRotateTask.apply_async(args=[filename, 360],
  133. routing_key="image.rotate")
  134. >>> ImageCropTask.apply_async(args=[filename, selection],
  135. routing_key="image.crop")
  136. >>> UpdateReccomendationsTask.apply_async(routing_key="misc.recommend")
  137. Later, if suddenly the image crop task is consuming a lot of resources,
  138. we can bind some new workers to handle just the ``"image.crop"`` task,
  139. by creating a new queue that binds to ``"image.crop``".
  140. AMQP options
  141. ------------
  142. * mandatory
  143. This sets the delivery to be mandatory. An exception will be raised
  144. if there are no running workers able to take on the task.
  145. * immediate
  146. Request immediate delivery. Will raise an exception
  147. if the task cannot be routed to a worker immediately.
  148. * priority
  149. A number between ``0`` and ``9``, where ``0`` is the highest priority.
  150. Note that RabbitMQ does not implement AMQP priorities, and maybe your broker
  151. does not either, please consult your brokers documentation for more
  152. information.