blob: 1c7bfeab37364ee364bf73f092b0a865b5189151 [file] [log] [blame]
Guido van Rossum4b8c6ea2000-02-04 15:39:30 +00001"""A generally useful event scheduler class.
Guido van Rossum2d844d11991-04-07 13:41:50 +00002
Fred Drake5c4012a1999-06-25 18:53:23 +00003Each instance of this class manages its own queue.
4No multi-threading is implied; you are supposed to hack that
5yourself, or use a single instance per application.
Guido van Rossum2d844d11991-04-07 13:41:50 +00006
Fred Drake5c4012a1999-06-25 18:53:23 +00007Each instance is parametrized with two functions, one that is
8supposed to return the current time, one that is supposed to
9implement a delay. You can implement real-time scheduling by
10substituting time and sleep from built-in module time, or you can
11implement simulated time by writing your own functions. This can
12also be used to integrate scheduling with STDWIN events; the delay
13function is allowed to modify the queue. Time can be expressed as
14integers or floating point numbers, as long as it is consistent.
15
16Events are specified by tuples (time, priority, action, argument).
17As in UNIX, lower priority numbers mean higher priority; in this
Raymond Hettingerbf72b712004-12-17 13:52:20 +000018way the queue can be maintained as a priority queue. Execution of the
Georg Brandla970c222007-10-08 08:06:05 +000019event means calling the action function, passing it the argument
20sequence in "argument" (remember that in Python, multiple function
21arguments are be packed in a sequence).
22The action function may be an instance method so it
Fred Drake5c4012a1999-06-25 18:53:23 +000023has another way to reference private data (besides global variables).
Fred Drake5c4012a1999-06-25 18:53:23 +000024"""
Guido van Rossum2d844d11991-04-07 13:41:50 +000025
Guido van Rossum5478cc61991-11-12 15:37:53 +000026# XXX The timefunc and delayfunc should have been defined as methods
27# XXX so you can define new kinds of schedulers using subclassing
28# XXX instead of having to define a module or class just to hold
Fred Drake5c4012a1999-06-25 18:53:23 +000029# XXX the global state of your particular time and delay functions.
Guido van Rossum5478cc61991-11-12 15:37:53 +000030
Raymond Hettingerbf72b712004-12-17 13:52:20 +000031import heapq
Raymond Hettinger44bd6c02008-01-17 19:31:38 +000032from collections import namedtuple
Guido van Rossum4e160981992-09-02 20:43:20 +000033
Skip Montanaro0de65802001-02-15 22:15:14 +000034__all__ = ["scheduler"]
35
Raymond Hettinger44bd6c02008-01-17 19:31:38 +000036Event = namedtuple('Event', 'time, priority, action, argument')
37
Guido van Rossumce084481991-12-26 13:06:29 +000038class scheduler:
Fred Drake5c4012a1999-06-25 18:53:23 +000039 def __init__(self, timefunc, delayfunc):
40 """Initialize a new instance, passing the time and delay
41 functions"""
Raymond Hettinger44bd6c02008-01-17 19:31:38 +000042 self._queue = []
Fred Drake5c4012a1999-06-25 18:53:23 +000043 self.timefunc = timefunc
44 self.delayfunc = delayfunc
45
46 def enterabs(self, time, priority, action, argument):
47 """Enter a new event in the queue at an absolute time.
48
Tim Peters495ad3c2001-01-15 01:36:40 +000049 Returns an ID for the event which can be used to remove it,
50 if necessary.
Fred Drake5c4012a1999-06-25 18:53:23 +000051
Tim Peters495ad3c2001-01-15 01:36:40 +000052 """
Raymond Hettinger44bd6c02008-01-17 19:31:38 +000053 event = Event(time, priority, action, argument)
54 heapq.heappush(self._queue, event)
Fred Drake5c4012a1999-06-25 18:53:23 +000055 return event # The ID
56
57 def enter(self, delay, priority, action, argument):
58 """A variant that specifies the time as a relative time.
59
Tim Peters495ad3c2001-01-15 01:36:40 +000060 This is actually the more commonly used interface.
Fred Drake5c4012a1999-06-25 18:53:23 +000061
Tim Peters495ad3c2001-01-15 01:36:40 +000062 """
Fred Drake5c4012a1999-06-25 18:53:23 +000063 time = self.timefunc() + delay
64 return self.enterabs(time, priority, action, argument)
65
66 def cancel(self, event):
67 """Remove an event from the queue.
68
Tim Peters495ad3c2001-01-15 01:36:40 +000069 This must be presented the ID as returned by enter().
70 If the event is not in the queue, this raises RuntimeError.
Fred Drake5c4012a1999-06-25 18:53:23 +000071
Tim Peters495ad3c2001-01-15 01:36:40 +000072 """
Raymond Hettinger44bd6c02008-01-17 19:31:38 +000073 self._queue.remove(event)
74 heapq.heapify(self._queue)
Fred Drake5c4012a1999-06-25 18:53:23 +000075
76 def empty(self):
77 """Check whether the queue is empty."""
Raymond Hettinger44bd6c02008-01-17 19:31:38 +000078 return not self._queue
Fred Drake5c4012a1999-06-25 18:53:23 +000079
80 def run(self):
81 """Execute events until the queue is empty.
Fred Drake5c4012a1999-06-25 18:53:23 +000082
Tim Peters495ad3c2001-01-15 01:36:40 +000083 When there is a positive delay until the first event, the
84 delay function is called and the event is left in the queue;
85 otherwise, the event is removed from the queue and executed
86 (its action function is called, passing it the argument). If
87 the delay function returns prematurely, it is simply
88 restarted.
Fred Drake5c4012a1999-06-25 18:53:23 +000089
Tim Peters495ad3c2001-01-15 01:36:40 +000090 It is legal for both the delay function and the action
91 function to to modify the queue or to raise an exception;
92 exceptions are not caught but the scheduler's state remains
93 well-defined so run() may be called again.
Fred Drake5c4012a1999-06-25 18:53:23 +000094
Georg Brandla970c222007-10-08 08:06:05 +000095 A questionable hack is added to allow other threads to run:
Tim Peters495ad3c2001-01-15 01:36:40 +000096 just after an event is executed, a delay of 0 is executed, to
97 avoid monopolizing the CPU when other threads are also
98 runnable.
99
100 """
Raymond Hettingerbf72b712004-12-17 13:52:20 +0000101 # localize variable access to minimize overhead
102 # and to improve thread safety
Raymond Hettinger44bd6c02008-01-17 19:31:38 +0000103 q = self._queue
Raymond Hettingerbf72b712004-12-17 13:52:20 +0000104 delayfunc = self.delayfunc
105 timefunc = self.timefunc
106 pop = heapq.heappop
Fred Drake5c4012a1999-06-25 18:53:23 +0000107 while q:
Raymond Hettingerbf72b712004-12-17 13:52:20 +0000108 time, priority, action, argument = checked_event = q[0]
109 now = timefunc()
Fred Drake5c4012a1999-06-25 18:53:23 +0000110 if now < time:
Raymond Hettingerbf72b712004-12-17 13:52:20 +0000111 delayfunc(time - now)
Fred Drake5c4012a1999-06-25 18:53:23 +0000112 else:
Raymond Hettingerbf72b712004-12-17 13:52:20 +0000113 event = pop(q)
114 # Verify that the event was not removed or altered
115 # by another thread after we last looked at q[0].
116 if event is checked_event:
Georg Brandla970c222007-10-08 08:06:05 +0000117 action(*argument)
Raymond Hettingerbf72b712004-12-17 13:52:20 +0000118 delayfunc(0) # Let other threads run
119 else:
120 heapq.heappush(event)
Raymond Hettinger44bd6c02008-01-17 19:31:38 +0000121
122 @property
123 def queue(self):
124 """An ordered list of upcoming events.
125
126 Events are named tuples with fields for:
127 time, priority, action, arguments
128
129 """
130 # Use heapq to sort the queue rather than using 'sorted(self._queue)'.
131 # With heapq, two events scheduled at the same time will show in
132 # the actual order they would be retrieved.
133 events = self._queue[:]
134 return map(heapq.heappop, [events]*len(events))