sched.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  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).
  14. As in UNIX, lower priority numbers mean higher priority; in this
  15. way the queue can be maintained fully sorted. Execution of the
  16. event means calling the action function, passing it the argument.
  17. Remember that in Python, multiple function arguments can be packed
  18. in a tuple. The action function may be an instance method so it
  19. has another way to reference private data (besides global variables).
  20. Parameterless functions or methods cannot be used, however.
  21. """
  22. # XXX The timefunc and delayfunc should have been defined as methods
  23. # XXX so you can define new kinds of schedulers using subclassing
  24. # XXX instead of having to define a module or class just to hold
  25. # XXX the global state of your particular time and delay functions.
  26. import bisect
  27. __all__ = ["scheduler"]
  28. class scheduler:
  29. def __init__(self, timefunc, delayfunc):
  30. """Initialize a new instance, passing the time and delay
  31. functions"""
  32. self.queue = []
  33. self.timefunc = timefunc
  34. self.delayfunc = delayfunc
  35. def enterabs(self, time, priority, action, argument):
  36. """Enter a new event in the queue at an absolute time.
  37. Returns an ID for the event which can be used to remove it,
  38. if necessary.
  39. """
  40. event = time, priority, action, argument
  41. bisect.insort(self.queue, event)
  42. return event # The ID
  43. def enter(self, delay, priority, action, argument):
  44. """A variant that specifies the time as a relative time.
  45. This is actually the more commonly used interface.
  46. """
  47. time = self.timefunc() + delay
  48. return self.enterabs(time, priority, action, argument)
  49. def cancel(self, event):
  50. """Remove an event from the queue.
  51. This must be presented the ID as returned by enter().
  52. If the event is not in the queue, this raises RuntimeError.
  53. """
  54. self.queue.remove(event)
  55. def empty(self):
  56. """Check whether the queue is empty."""
  57. return len(self.queue) == 0
  58. def run(self):
  59. """Execute events until the queue is empty.
  60. When there is a positive delay until the first event, the
  61. delay function is called and the event is left in the queue;
  62. otherwise, the event is removed from the queue and executed
  63. (its action function is called, passing it the argument). If
  64. the delay function returns prematurely, it is simply
  65. restarted.
  66. It is legal for both the delay function and the action
  67. function to to modify the queue or to raise an exception;
  68. exceptions are not caught but the scheduler's state remains
  69. well-defined so run() may be called again.
  70. A questionably hack is added to allow other threads to run:
  71. just after an event is executed, a delay of 0 is executed, to
  72. avoid monopolizing the CPU when other threads are also
  73. runnable.
  74. """
  75. q = self.queue
  76. while q:
  77. time, priority, action, argument = q[0]
  78. now = self.timefunc()
  79. if now < time:
  80. self.delayfunc(time - now)
  81. else:
  82. del q[0]
  83. void = action(*argument)
  84. self.delayfunc(0) # Let other threads run