blob: 3e41198c105ea7c3d2da5994c43cf897a341b7d6 [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
Guido van Rossum8ce8a782007-11-01 19:42:39 +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
Giampaolo Rodola'be55d992011-11-22 13:33:34 +010031import time
Raymond Hettingerbf72b712004-12-17 13:52:20 +000032import heapq
Christian Heimes679db4a2008-01-18 09:56:22 +000033from collections import namedtuple
Guido van Rossum4e160981992-09-02 20:43:20 +000034
Skip Montanaro0de65802001-02-15 22:15:14 +000035__all__ = ["scheduler"]
36
Giampaolo Rodola'be55d992011-11-22 13:33:34 +010037class Event(namedtuple('Event', 'time, priority, action, argument, kwargs')):
Giampaolo Rodola'f6837002011-11-22 21:19:37 +010038 def __init__(self, *args, **kwargs):
39 super(Event, self).__init__(*args, **kwargs)
40 self._scheduled = False
Raymond Hettinger8f40e092009-04-24 18:43:43 +000041 def __eq__(s, o): return (s.time, s.priority) == (o.time, o.priority)
42 def __ne__(s, o): return (s.time, s.priority) != (o.time, o.priority)
43 def __lt__(s, o): return (s.time, s.priority) < (o.time, o.priority)
44 def __le__(s, o): return (s.time, s.priority) <= (o.time, o.priority)
45 def __gt__(s, o): return (s.time, s.priority) > (o.time, o.priority)
46 def __ge__(s, o): return (s.time, s.priority) >= (o.time, o.priority)
Christian Heimes679db4a2008-01-18 09:56:22 +000047
Guido van Rossumce084481991-12-26 13:06:29 +000048class scheduler:
Giampaolo Rodola'be55d992011-11-22 13:33:34 +010049
50 def __init__(self, timefunc=time.time, delayfunc=time.sleep):
Fred Drake5c4012a1999-06-25 18:53:23 +000051 """Initialize a new instance, passing the time and delay
52 functions"""
Christian Heimes679db4a2008-01-18 09:56:22 +000053 self._queue = []
Fred Drake5c4012a1999-06-25 18:53:23 +000054 self.timefunc = timefunc
55 self.delayfunc = delayfunc
56
Giampaolo Rodola'be55d992011-11-22 13:33:34 +010057 def enterabs(self, time, priority, action, argument=[], kwargs={}):
Fred Drake5c4012a1999-06-25 18:53:23 +000058 """Enter a new event in the queue at an absolute time.
59
Tim Peters495ad3c2001-01-15 01:36:40 +000060 Returns an ID for the event which can be used to remove it,
61 if necessary.
Fred Drake5c4012a1999-06-25 18:53:23 +000062
Tim Peters495ad3c2001-01-15 01:36:40 +000063 """
Giampaolo Rodola'be55d992011-11-22 13:33:34 +010064 event = Event(time, priority, action, argument, kwargs)
Giampaolo Rodola'f6837002011-11-22 21:19:37 +010065 event._scheduled = True
Christian Heimes679db4a2008-01-18 09:56:22 +000066 heapq.heappush(self._queue, event)
Fred Drake5c4012a1999-06-25 18:53:23 +000067 return event # The ID
68
Giampaolo Rodola'be55d992011-11-22 13:33:34 +010069 def enter(self, delay, priority, action, argument=[], kwargs={}):
Fred Drake5c4012a1999-06-25 18:53:23 +000070 """A variant that specifies the time as a relative time.
71
Tim Peters495ad3c2001-01-15 01:36:40 +000072 This is actually the more commonly used interface.
Fred Drake5c4012a1999-06-25 18:53:23 +000073
Tim Peters495ad3c2001-01-15 01:36:40 +000074 """
Fred Drake5c4012a1999-06-25 18:53:23 +000075 time = self.timefunc() + delay
Giampaolo Rodola'be55d992011-11-22 13:33:34 +010076 return self.enterabs(time, priority, action, argument, kwargs)
Fred Drake5c4012a1999-06-25 18:53:23 +000077
78 def cancel(self, event):
79 """Remove an event from the queue.
80
Tim Peters495ad3c2001-01-15 01:36:40 +000081 This must be presented the ID as returned by enter().
Georg Brandlc38a0002009-05-26 07:51:03 +000082 If the event is not in the queue, this raises ValueError.
Fred Drake5c4012a1999-06-25 18:53:23 +000083
Tim Peters495ad3c2001-01-15 01:36:40 +000084 """
Christian Heimes679db4a2008-01-18 09:56:22 +000085 self._queue.remove(event)
86 heapq.heapify(self._queue)
Fred Drake5c4012a1999-06-25 18:53:23 +000087
Giampaolo Rodola'f6837002011-11-22 21:19:37 +010088 def is_scheduled(self, event):
89 return event._scheduled
90
Fred Drake5c4012a1999-06-25 18:53:23 +000091 def empty(self):
92 """Check whether the queue is empty."""
Christian Heimes679db4a2008-01-18 09:56:22 +000093 return not self._queue
Fred Drake5c4012a1999-06-25 18:53:23 +000094
95 def run(self):
96 """Execute events until the queue is empty.
Fred Drake5c4012a1999-06-25 18:53:23 +000097
Tim Peters495ad3c2001-01-15 01:36:40 +000098 When there is a positive delay until the first event, the
99 delay function is called and the event is left in the queue;
100 otherwise, the event is removed from the queue and executed
101 (its action function is called, passing it the argument). If
102 the delay function returns prematurely, it is simply
103 restarted.
Fred Drake5c4012a1999-06-25 18:53:23 +0000104
Tim Peters495ad3c2001-01-15 01:36:40 +0000105 It is legal for both the delay function and the action
Ezio Melottie130a522011-10-19 10:58:56 +0300106 function to modify the queue or to raise an exception;
Tim Peters495ad3c2001-01-15 01:36:40 +0000107 exceptions are not caught but the scheduler's state remains
108 well-defined so run() may be called again.
Fred Drake5c4012a1999-06-25 18:53:23 +0000109
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000110 A questionable hack is added to allow other threads to run:
Tim Peters495ad3c2001-01-15 01:36:40 +0000111 just after an event is executed, a delay of 0 is executed, to
112 avoid monopolizing the CPU when other threads are also
113 runnable.
114
115 """
Raymond Hettingerbf72b712004-12-17 13:52:20 +0000116 # localize variable access to minimize overhead
117 # and to improve thread safety
Christian Heimes679db4a2008-01-18 09:56:22 +0000118 q = self._queue
Raymond Hettingerbf72b712004-12-17 13:52:20 +0000119 delayfunc = self.delayfunc
120 timefunc = self.timefunc
121 pop = heapq.heappop
Fred Drake5c4012a1999-06-25 18:53:23 +0000122 while q:
Giampaolo Rodola'be55d992011-11-22 13:33:34 +0100123 time, priority, action, argument, kwargs = checked_event = q[0]
Raymond Hettingerbf72b712004-12-17 13:52:20 +0000124 now = timefunc()
Fred Drake5c4012a1999-06-25 18:53:23 +0000125 if now < time:
Raymond Hettingerbf72b712004-12-17 13:52:20 +0000126 delayfunc(time - now)
Fred Drake5c4012a1999-06-25 18:53:23 +0000127 else:
Raymond Hettingerbf72b712004-12-17 13:52:20 +0000128 event = pop(q)
129 # Verify that the event was not removed or altered
130 # by another thread after we last looked at q[0].
131 if event is checked_event:
Giampaolo Rodola'f6837002011-11-22 21:19:37 +0100132 event._scheduled = False
Giampaolo Rodola'be55d992011-11-22 13:33:34 +0100133 action(*argument, **kwargs)
Raymond Hettingerbf72b712004-12-17 13:52:20 +0000134 delayfunc(0) # Let other threads run
135 else:
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +0000136 heapq.heappush(q, event)
Christian Heimes679db4a2008-01-18 09:56:22 +0000137
138 @property
139 def queue(self):
140 """An ordered list of upcoming events.
141
142 Events are named tuples with fields for:
143 time, priority, action, arguments
144
145 """
146 # Use heapq to sort the queue rather than using 'sorted(self._queue)'.
147 # With heapq, two events scheduled at the same time will show in
148 # the actual order they would be retrieved.
149 events = self._queue[:]
150 return map(heapq.heappop, [events]*len(events))