blob: 14613cf29874da539490accd7d83abce51499964 [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
Serhiy Storchakae9124962012-12-29 20:57:52 +020016Events are specified by tuples (time, priority, action, argument, kwargs).
Fred Drake5c4012a1999-06-25 18:53:23 +000017As 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
Serhiy Storchakae9124962012-12-29 20:57:52 +020021arguments are be packed in a sequence) and keyword parameters in "kwargs".
Guido van Rossum8ce8a782007-11-01 19:42:39 +000022The 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
Giampaolo Rodola'be55d992011-11-22 13:33:34 +010026import time
Raymond Hettingerbf72b712004-12-17 13:52:20 +000027import heapq
Christian Heimes679db4a2008-01-18 09:56:22 +000028from collections import namedtuple
Bar Harel5368c2b2020-10-19 10:33:43 +030029from itertools import count
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020030import threading
Victor Stinnerae586492014-09-02 23:18:25 +020031from time import monotonic as _time
Guido van Rossum4e160981992-09-02 20:43:20 +000032
Skip Montanaro0de65802001-02-15 22:15:14 +000033__all__ = ["scheduler"]
34
Bar Harel5368c2b2020-10-19 10:33:43 +030035Event = namedtuple('Event', 'time, priority, sequence, action, argument, kwargs')
Raymond Hettinger5b798ab2015-08-17 22:04:45 -070036Event.time.__doc__ = ('''Numeric type compatible with the return value of the
37timefunc function passed to the constructor.''')
38Event.priority.__doc__ = ('''Events scheduled for the same time will be executed
39in the order of their priority.''')
Bar Harel5368c2b2020-10-19 10:33:43 +030040Event.sequence.__doc__ = ('''A continually increasing sequence number that
41 separates events if time and priority are equal.''')
Raymond Hettinger5b798ab2015-08-17 22:04:45 -070042Event.action.__doc__ = ('''Executing the event means executing
43action(*argument, **kwargs)''')
44Event.argument.__doc__ = ('''argument is a sequence holding the positional
45arguments for the action.''')
46Event.kwargs.__doc__ = ('''kwargs is a dictionary holding the keyword
47arguments for the action.''')
48
Serhiy Storchakac04957b2012-12-29 21:13:45 +020049_sentinel = object()
50
Guido van Rossumce084481991-12-26 13:06:29 +000051class scheduler:
Giampaolo Rodola'be55d992011-11-22 13:33:34 +010052
Victor Stinner949d8c92012-05-30 13:30:32 +020053 def __init__(self, timefunc=_time, delayfunc=time.sleep):
Fred Drake5c4012a1999-06-25 18:53:23 +000054 """Initialize a new instance, passing the time and delay
55 functions"""
Christian Heimes679db4a2008-01-18 09:56:22 +000056 self._queue = []
Giampaolo Rodola'73520d52011-12-14 13:34:26 +010057 self._lock = threading.RLock()
Fred Drake5c4012a1999-06-25 18:53:23 +000058 self.timefunc = timefunc
59 self.delayfunc = delayfunc
Bar Harel5368c2b2020-10-19 10:33:43 +030060 self._sequence_generator = count()
Fred Drake5c4012a1999-06-25 18:53:23 +000061
Serhiy Storchakac04957b2012-12-29 21:13:45 +020062 def enterabs(self, time, priority, action, argument=(), kwargs=_sentinel):
Fred Drake5c4012a1999-06-25 18:53:23 +000063 """Enter a new event in the queue at an absolute time.
64
Tim Peters495ad3c2001-01-15 01:36:40 +000065 Returns an ID for the event which can be used to remove it,
66 if necessary.
Fred Drake5c4012a1999-06-25 18:53:23 +000067
Tim Peters495ad3c2001-01-15 01:36:40 +000068 """
Serhiy Storchakac04957b2012-12-29 21:13:45 +020069 if kwargs is _sentinel:
70 kwargs = {}
Bar Harel5368c2b2020-10-19 10:33:43 +030071
Giampaolo Rodola'73520d52011-12-14 13:34:26 +010072 with self._lock:
Bar Harel5368c2b2020-10-19 10:33:43 +030073 event = Event(time, priority, next(self._sequence_generator),
74 action, argument, kwargs)
Giampaolo Rodola'73520d52011-12-14 13:34:26 +010075 heapq.heappush(self._queue, event)
Serhiy Storchakad07db962012-12-29 21:46:37 +020076 return event # The ID
Fred Drake5c4012a1999-06-25 18:53:23 +000077
Serhiy Storchakac04957b2012-12-29 21:13:45 +020078 def enter(self, delay, priority, action, argument=(), kwargs=_sentinel):
Fred Drake5c4012a1999-06-25 18:53:23 +000079 """A variant that specifies the time as a relative time.
80
Tim Peters495ad3c2001-01-15 01:36:40 +000081 This is actually the more commonly used interface.
Fred Drake5c4012a1999-06-25 18:53:23 +000082
Tim Peters495ad3c2001-01-15 01:36:40 +000083 """
Serhiy Storchakad07db962012-12-29 21:46:37 +020084 time = self.timefunc() + delay
85 return self.enterabs(time, priority, action, argument, kwargs)
Fred Drake5c4012a1999-06-25 18:53:23 +000086
87 def cancel(self, event):
88 """Remove an event from the queue.
89
Tim Peters495ad3c2001-01-15 01:36:40 +000090 This must be presented the ID as returned by enter().
Georg Brandlc38a0002009-05-26 07:51:03 +000091 If the event is not in the queue, this raises ValueError.
Fred Drake5c4012a1999-06-25 18:53:23 +000092
Tim Peters495ad3c2001-01-15 01:36:40 +000093 """
Giampaolo Rodola'73520d52011-12-14 13:34:26 +010094 with self._lock:
95 self._queue.remove(event)
96 heapq.heapify(self._queue)
Fred Drake5c4012a1999-06-25 18:53:23 +000097
98 def empty(self):
99 """Check whether the queue is empty."""
Giampaolo Rodola'73520d52011-12-14 13:34:26 +0100100 with self._lock:
101 return not self._queue
Fred Drake5c4012a1999-06-25 18:53:23 +0000102
Giampaolo Rodola'556ba042011-12-14 14:38:45 +0100103 def run(self, blocking=True):
Fred Drake5c4012a1999-06-25 18:53:23 +0000104 """Execute events until the queue is empty.
Giampaolo Rodola'556ba042011-12-14 14:38:45 +0100105 If blocking is False executes the scheduled events due to
Giampaolo Rodola'a4e01882012-03-15 13:05:41 +0100106 expire soonest (if any) and then return the deadline of the
107 next scheduled call in the scheduler.
Fred Drake5c4012a1999-06-25 18:53:23 +0000108
Tim Peters495ad3c2001-01-15 01:36:40 +0000109 When there is a positive delay until the first event, the
110 delay function is called and the event is left in the queue;
111 otherwise, the event is removed from the queue and executed
112 (its action function is called, passing it the argument). If
113 the delay function returns prematurely, it is simply
114 restarted.
Fred Drake5c4012a1999-06-25 18:53:23 +0000115
Tim Peters495ad3c2001-01-15 01:36:40 +0000116 It is legal for both the delay function and the action
Ezio Melottie130a522011-10-19 10:58:56 +0300117 function to modify the queue or to raise an exception;
Tim Peters495ad3c2001-01-15 01:36:40 +0000118 exceptions are not caught but the scheduler's state remains
119 well-defined so run() may be called again.
Fred Drake5c4012a1999-06-25 18:53:23 +0000120
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000121 A questionable hack is added to allow other threads to run:
Tim Peters495ad3c2001-01-15 01:36:40 +0000122 just after an event is executed, a delay of 0 is executed, to
123 avoid monopolizing the CPU when other threads are also
124 runnable.
125
126 """
Raymond Hettingerbf72b712004-12-17 13:52:20 +0000127 # localize variable access to minimize overhead
128 # and to improve thread safety
Serhiy Storchakaf2b9cf42012-12-29 21:34:11 +0200129 lock = self._lock
130 q = self._queue
131 delayfunc = self.delayfunc
132 timefunc = self.timefunc
133 pop = heapq.heappop
134 while True:
135 with lock:
136 if not q:
137 break
Bar Harel5368c2b2020-10-19 10:33:43 +0300138 (time, priority, sequence, action,
139 argument, kwargs) = q[0]
Giampaolo Rodola'73520d52011-12-14 13:34:26 +0100140 now = timefunc()
Serhiy Storchakaf2b9cf42012-12-29 21:34:11 +0200141 if time > now:
142 delay = True
Raymond Hettingerbf72b712004-12-17 13:52:20 +0000143 else:
Serhiy Storchakaf2b9cf42012-12-29 21:34:11 +0200144 delay = False
145 pop(q)
146 if delay:
147 if not blocking:
148 return time - now
149 delayfunc(time - now)
150 else:
151 action(*argument, **kwargs)
152 delayfunc(0) # Let other threads run
Christian Heimes679db4a2008-01-18 09:56:22 +0000153
154 @property
155 def queue(self):
156 """An ordered list of upcoming events.
157
158 Events are named tuples with fields for:
Serhiy Storchakae9124962012-12-29 20:57:52 +0200159 time, priority, action, arguments, kwargs
Christian Heimes679db4a2008-01-18 09:56:22 +0000160
161 """
162 # Use heapq to sort the queue rather than using 'sorted(self._queue)'.
163 # With heapq, two events scheduled at the same time will show in
164 # the actual order they would be retrieved.
Giampaolo Rodola'73520d52011-12-14 13:34:26 +0100165 with self._lock:
166 events = self._queue[:]
Raymond Hettinger468bcaf2013-07-13 22:48:49 -0700167 return list(map(heapq.heappop, [events]*len(events)))