tasksets.rst 7.1 KB

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