sched.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. """A generally useful event scheduler class.
  2. Each instance of this class manages its own queue.
  3. No multi-threading is implied; you are supposed to hack that
  4. yourself, or use a single instance per application.
  5. Each instance is parametrized with two functions, one that is
  6. supposed to return the current time, one that is supposed to
  7. implement a delay. You can implement real-time scheduling by
  8. substituting time and sleep from built-in module time, or you can
  9. implement simulated time by writing your own functions. This can
  10. also be used to integrate scheduling with STDWIN events; the delay
  11. function is allowed to modify the queue. Time can be expressed as
  12. integers or floating point numbers, as long as it is consistent.
  13. Events are specified by tuples (time, priority, action, argument, kwargs).
  14. As in UNIX, lower priority numbers mean higher priority; in this
  15. way the queue can be maintained as a priority queue. Execution of the
  16. event means calling the action function, passing it the argument
  17. sequence in "argument" (remember that in Python, multiple function
  18. arguments are be packed in a sequence) and keyword parameters in "kwargs".
  19. The action function may be an instance method so it
  20. has another way to reference private data (besides global variables).
  21. """
  22. import time
  23. import heapq
  24. from collections import namedtuple
  25. import threading
  26. from time import monotonic as _time
  27. __all__ = ["scheduler"]
  28. class Event(namedtuple('Event', 'time, priority, action, argument, kwargs')):
  29. __slots__ = []
  30. def __eq__(s, o): return (s.time, s.priority) == (o.time, o.priority)
  31. def __lt__(s, o): return (s.time, s.priority) < (o.time, o.priority)
  32. def __le__(s, o): return (s.time, s.priority) <= (o.time, o.priority)
  33. def __gt__(s, o): return (s.time, s.priority) > (o.time, o.priority)
  34. def __ge__(s, o): return (s.time, s.priority) >= (o.time, o.priority)
  35. Event.time.__doc__ = ('''Numeric type compatible with the return value of the
  36. timefunc function passed to the constructor.''')
  37. Event.priority.__doc__ = ('''Events scheduled for the same time will be executed
  38. in the order of their priority.''')
  39. Event.action.__doc__ = ('''Executing the event means executing
  40. action(*argument, **kwargs)''')
  41. Event.argument.__doc__ = ('''argument is a sequence holding the positional
  42. arguments for the action.''')
  43. Event.kwargs.__doc__ = ('''kwargs is a dictionary holding the keyword
  44. arguments for the action.''')
  45. _sentinel = object()
  46. class scheduler:
  47. def __init__(self, timefunc=_time, delayfunc=time.sleep):
  48. """Initialize a new instance, passing the time and delay
  49. functions"""
  50. self._queue = []
  51. self._lock = threading.RLock()
  52. self.timefunc = timefunc
  53. self.delayfunc = delayfunc
  54. def enterabs(self, time, priority, action, argument=(), kwargs=_sentinel):
  55. """Enter a new event in the queue at an absolute time.
  56. Returns an ID for the event which can be used to remove it,
  57. if necessary.
  58. """
  59. if kwargs is _sentinel:
  60. kwargs = {}
  61. event = Event(time, priority, action, argument, kwargs)
  62. with self._lock:
  63. heapq.heappush(self._queue, event)
  64. return event # The ID
  65. def enter(self, delay, priority, action, argument=(), kwargs=_sentinel):
  66. """A variant that specifies the time as a relative time.
  67. This is actually the more commonly used interface.
  68. """
  69. time = self.timefunc() + delay
  70. return self.enterabs(time, priority, action, argument, kwargs)
  71. def cancel(self, event):
  72. """Remove an event from the queue.
  73. This must be presented the ID as returned by enter().
  74. If the event is not in the queue, this raises ValueError.
  75. """
  76. with self._lock:
  77. self._queue.remove(event)
  78. heapq.heapify(self._queue)
  79. def empty(self):
  80. """Check whether the queue is empty."""
  81. with self._lock:
  82. return not self._queue
  83. def run(self, blocking=True):
  84. """Execute events until the queue is empty.
  85. If blocking is False executes the scheduled events due to
  86. expire soonest (if any) and then return the deadline of the
  87. next scheduled call in the scheduler.
  88. When there is a positive delay until the first event, the
  89. delay function is called and the event is left in the queue;
  90. otherwise, the event is removed from the queue and executed
  91. (its action function is called, passing it the argument). If
  92. the delay function returns prematurely, it is simply
  93. restarted.
  94. It is legal for both the delay function and the action
  95. function to modify the queue or to raise an exception;
  96. exceptions are not caught but the scheduler's state remains
  97. well-defined so run() may be called again.
  98. A questionable hack is added to allow other threads to run:
  99. just after an event is executed, a delay of 0 is executed, to
  100. avoid monopolizing the CPU when other threads are also
  101. runnable.
  102. """
  103. # localize variable access to minimize overhead
  104. # and to improve thread safety
  105. lock = self._lock
  106. q = self._queue
  107. delayfunc = self.delayfunc
  108. timefunc = self.timefunc
  109. pop = heapq.heappop
  110. while True:
  111. with lock:
  112. if not q:
  113. break
  114. time, priority, action, argument, kwargs = q[0]
  115. now = timefunc()
  116. if time > now:
  117. delay = True
  118. else:
  119. delay = False
  120. pop(q)
  121. if delay:
  122. if not blocking:
  123. return time - now
  124. delayfunc(time - now)
  125. else:
  126. action(*argument, **kwargs)
  127. delayfunc(0) # Let other threads run
  128. @property
  129. def queue(self):
  130. """An ordered list of upcoming events.
  131. Events are named tuples with fields for:
  132. time, priority, action, arguments, kwargs
  133. """
  134. # Use heapq to sort the queue rather than using 'sorted(self._queue)'.
  135. # With heapq, two events scheduled at the same time will show in
  136. # the actual order they would be retrieved.
  137. with self._lock:
  138. events = self._queue[:]
  139. return list(map(heapq.heappop, [events]*len(events)))