sets.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. # -*- coding: utf-8 -*-
  2. """
  3. celery.task.sets
  4. ~~~~~~~~~~~~~~~~
  5. Old ``group`` implementation, this module should
  6. not be used anymore use :func:`celery.group` instead.
  7. """
  8. from __future__ import absolute_import
  9. from celery._state import get_current_worker_task
  10. from celery.app import app_or_default
  11. from celery.canvas import subtask, maybe_subtask # noqa
  12. from celery.utils import uuid, warn_deprecated
  13. warn_deprecated(
  14. 'celery.task.sets and TaskSet', removal='4.0',
  15. alternative="""\
  16. Please use "group" instead (see the Canvas section in the userguide)\
  17. """)
  18. class TaskSet(list):
  19. """A task containing several subtasks, making it possible
  20. to track how many, or when all of the tasks have been completed.
  21. :param tasks: A list of :class:`subtask` instances.
  22. Example::
  23. >>> urls = ('http://cnn.com/rss', 'http://bbc.co.uk/rss')
  24. >>> s = TaskSet(refresh_feed.s(url) for url in urls)
  25. >>> taskset_result = s.apply_async()
  26. >>> list_of_return_values = taskset_result.join() # *expensive*
  27. """
  28. app = None
  29. def __init__(self, tasks=None, app=None, Publisher=None):
  30. super(TaskSet, self).__init__(maybe_subtask(t) for t in tasks or [])
  31. self.app = app_or_default(app or self.app)
  32. self.Publisher = Publisher or self.app.amqp.TaskProducer
  33. self.total = len(self) # XXX compat
  34. def apply_async(self, connection=None, publisher=None, taskset_id=None):
  35. """Apply TaskSet."""
  36. app = self.app
  37. if app.conf.CELERY_ALWAYS_EAGER:
  38. return self.apply(taskset_id=taskset_id)
  39. with app.connection_or_acquire(connection) as conn:
  40. setid = taskset_id or uuid()
  41. pub = publisher or self.Publisher(conn)
  42. results = self._async_results(setid, pub)
  43. result = app.TaskSetResult(setid, results)
  44. parent = get_current_worker_task()
  45. if parent:
  46. parent.add_trail(result)
  47. return result
  48. def _async_results(self, taskset_id, publisher):
  49. return [task.apply_async(taskset_id=taskset_id, publisher=publisher)
  50. for task in self]
  51. def apply(self, taskset_id=None):
  52. """Applies the TaskSet locally by blocking until all tasks return."""
  53. setid = taskset_id or uuid()
  54. return self.app.TaskSetResult(setid, self._sync_results(setid))
  55. def _sync_results(self, taskset_id):
  56. return [task.apply(taskset_id=taskset_id) for task in self]
  57. @property
  58. def tasks(self):
  59. return self
  60. @tasks.setter # noqa
  61. def tasks(self, tasks):
  62. self[:] = tasks