tasksets.rst 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. .. _guide-sets:
  2. =======================================
  3. Groups, Chords, Chains and Callbacks
  4. =======================================
  5. .. contents::
  6. :local:
  7. .. _sets-subtasks:
  8. Subtasks
  9. ========
  10. .. versionadded:: 2.0
  11. The :class:`~celery.task.sets.subtask` type is used to wrap the arguments and
  12. execution options for a single task invocation:
  13. .. code-block:: python
  14. from celery import subtask
  15. subtask(task_name_or_cls, args, kwargs, options)
  16. For convenience every task also has a shortcut to create subtasks:
  17. .. code-block:: python
  18. task.subtask(args, kwargs, options)
  19. :class:`~celery.task.sets.subtask` is actually a :class:`dict` subclass,
  20. which means it can be serialized with JSON or other encodings that doesn't
  21. support complex Python objects.
  22. Also it can be regarded as a type, as the following usage works::
  23. >>> s = subtask("tasks.add", args=(2, 2), kwargs={})
  24. >>> subtask(dict(s)) # coerce dict into subtask
  25. This makes it excellent as a means to pass callbacks around to tasks.
  26. .. _sets-callbacks:
  27. Callbacks
  28. ---------
  29. Callbacks can be added to any task using the ``link`` argument
  30. to ``apply_async``:
  31. add.apply_async((2, 2), link=other_task.subtask())
  32. The callback will only be applied if the task exited successfully,
  33. and it will be applied with the return value of the parent task as argument.
  34. The best thing is that any arguments you add to `subtask`,
  35. will be prepended to the arguments specified by the subtask itself!
  36. If you have the subtask::
  37. >>> add.subtask(args=(10, ))
  38. `subtask.delay(result)` becomes::
  39. >>> add.apply_async(args=(result, 10))
  40. ...
  41. Now let's execute our ``add`` task with a callback using partial
  42. arguments::
  43. >>> add.apply_async((2, 2), link=add.subtask((8, )))
  44. As expected this will first launch one task calculating :math:`2 + 2`, then
  45. another task calculating :math:`4 + 8`.
  46. .. _sets-taskset:
  47. Groups
  48. ======
  49. The :class:`~celery.task.sets.group` enables easy invocation of several
  50. tasks at once, and is then able to join the results in the same order as the
  51. tasks were invoked.
  52. ``group`` takes a list of :class:`~celery.task.sets.subtask`'s::
  53. >>> from celery import group
  54. >>> from tasks import add
  55. >>> job = group([
  56. ... add.subtask((4, 4)),
  57. ... add.subtask((8, 8)),
  58. ... add.subtask((16, 16)),
  59. ... add.subtask((32, 32)),
  60. ... ])
  61. >>> result = job.apply_async()
  62. >>> result.ready() # have all subtasks completed?
  63. True
  64. >>> result.successful() # were all subtasks successful?
  65. True
  66. >>> result.join()
  67. [4, 8, 16, 32, 64]
  68. The first argument can alternatively be an iterator, like::
  69. >>> group(add.subtask((i, i)) for i in range(100))
  70. .. _sets-results:
  71. Results
  72. -------
  73. When a :class:`~celery.task.sets.group` is applied it returns a
  74. :class:`~celery.result.TaskSetResult` object.
  75. :class:`~celery.result.TaskSetResult` takes a list of
  76. :class:`~celery.result.AsyncResult` instances and operates on them as if it was a
  77. single task.
  78. It supports the following operations:
  79. * :meth:`~celery.result.TaskSetResult.successful`
  80. Returns :const:`True` if all of the subtasks finished
  81. successfully (e.g. did not raise an exception).
  82. * :meth:`~celery.result.TaskSetResult.failed`
  83. Returns :const:`True` if any of the subtasks failed.
  84. * :meth:`~celery.result.TaskSetResult.waiting`
  85. Returns :const:`True` if any of the subtasks
  86. is not ready yet.
  87. * :meth:`~celery.result.TaskSetResult.ready`
  88. Return :const:`True` if all of the subtasks
  89. are ready.
  90. * :meth:`~celery.result.TaskSetResult.completed_count`
  91. Returns the number of completed subtasks.
  92. * :meth:`~celery.result.TaskSetResult.revoke`
  93. Revokes all of the subtasks.
  94. * :meth:`~celery.result.TaskSetResult.iterate`
  95. Iterates over the return values of the subtasks
  96. as they finish, one by one.
  97. * :meth:`~celery.result.TaskSetResult.join`
  98. Gather the results for all of the subtasks
  99. and return a list with them ordered by the order of which they
  100. were called.
  101. .. _chords:
  102. Chords
  103. ======
  104. .. versionadded:: 2.3
  105. A chord is a task that only executes after all of the tasks in a taskset has
  106. finished executing.
  107. Let's calculate the sum of the expression
  108. :math:`1 + 1 + 2 + 2 + 3 + 3 ... n + n` up to a hundred digits.
  109. First we need two tasks, :func:`add` and :func:`tsum` (:func:`sum` is
  110. already a standard function):
  111. .. code-block:: python
  112. @celery.task
  113. def add(x, y):
  114. return x + y
  115. @celery.task
  116. def tsum(numbers):
  117. return sum(numbers)
  118. Now we can use a chord to calculate each addition step in parallel, and then
  119. get the sum of the resulting numbers::
  120. >>> from celery import chord
  121. >>> from tasks import add, tsum
  122. >>> chord(add.subtask((i, i))
  123. ... for i in xrange(100))(tsum.subtask()).get()
  124. 9900
  125. This is obviously a very contrived example, the overhead of messaging and
  126. synchronization makes this a lot slower than its Python counterpart::
  127. sum(i + i for i in xrange(100))
  128. The synchronization step is costly, so you should avoid using chords as much
  129. as possible. Still, the chord is a powerful primitive to have in your toolbox
  130. as synchronization is a required step for many parallel algorithms.
  131. Let's break the chord expression down::
  132. >>> callback = tsum.subtask()
  133. >>> header = [add.subtask((i, i)) for i in xrange(100)]
  134. >>> result = chord(header)(callback)
  135. >>> result.get()
  136. 9900
  137. Remember, the callback can only be executed after all of the tasks in the
  138. header has returned. Each step in the header is executed as a task, in
  139. parallel, possibly on different nodes. The callback is then applied with
  140. the return value of each task in the header. The task id returned by
  141. :meth:`chord` is the id of the callback, so you can wait for it to complete
  142. and get the final return value (but remember to :ref:`never have a task wait
  143. for other tasks <task-synchronous-subtasks>`)
  144. .. _chord-important-notes:
  145. Important Notes
  146. ---------------
  147. By default the synchronization step is implemented by having a recurring task
  148. poll the completion of the taskset every second, applying the subtask when
  149. ready.
  150. Example implementation:
  151. .. code-block:: python
  152. def unlock_chord(taskset, callback, interval=1, max_retries=None):
  153. if taskset.ready():
  154. return subtask(callback).delay(taskset.join())
  155. unlock_chord.retry(countdown=interval, max_retries=max_retries)
  156. This is used by all result backends except Redis and Memcached, which increment a
  157. counter after each task in the header, then applying the callback when the
  158. counter exceeds the number of tasks in the set. *Note:* chords do not properly
  159. work with Redis before version 2.2; you will need to upgrade to at least 2.2 to
  160. use them.
  161. The Redis and Memcached approach is a much better solution, but not easily
  162. implemented in other backends (suggestions welcome!).
  163. .. note::
  164. If you are using chords with the Redis result backend and also overriding
  165. the :meth:`Task.after_return` method, you need to make sure to call the
  166. super method or else the chord callback will not be applied.
  167. .. code-block:: python
  168. def after_return(self, *args, **kwargs):
  169. do_something()
  170. super(MyTask, self).after_return(*args, **kwargs)