Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

scheduling.py 1.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. """
  2. kombu.transport.virtual.scheduling
  3. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  4. Consumer utilities.
  5. """
  6. from __future__ import absolute_import
  7. from itertools import count
  8. class FairCycle(object):
  9. """Consume from a set of resources, where each resource gets
  10. an equal chance to be consumed from."""
  11. def __init__(self, fun, resources, predicate=Exception):
  12. self.fun = fun
  13. self.resources = resources
  14. self.predicate = predicate
  15. self.pos = 0
  16. def _next(self):
  17. while 1:
  18. try:
  19. resource = self.resources[self.pos]
  20. self.pos += 1
  21. return resource
  22. except IndexError:
  23. self.pos = 0
  24. if not self.resources:
  25. raise self.predicate()
  26. def get(self, **kwargs):
  27. for tried in count(0): # for infinity
  28. resource = self._next()
  29. try:
  30. return self.fun(resource, **kwargs), resource
  31. except self.predicate:
  32. if tried >= len(self.resources) - 1:
  33. raise
  34. def close(self):
  35. pass
  36. def __repr__(self):
  37. return '<FairCycle: {self.pos}/{size} {self.resources}>'.format(
  38. self=self, size=len(self.resources))