github.com/grumpyhome/grumpy@v0.3.1-0.20201208125205-7b775405bdf1/grumpy-runtime-src/third_party/stdlib/sched.py (about) 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 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). 19 The action function may be an instance method so it 20 has another way to reference private data (besides global variables). 21 """ 22 23 # XXX The timefunc and delayfunc should have been defined as methods 24 # XXX so you can define new kinds of schedulers using subclassing 25 # XXX instead of having to define a module or class just to hold 26 # XXX the global state of your particular time and delay functions. 27 28 import heapq 29 # TODO: grumpy modified version 30 #from collections import namedtuple 31 32 __all__ = ["scheduler"] 33 34 # TODO: Use namedtuple 35 # Event = namedtuple('Event', 'time, priority, action, argument') 36 37 class Event(object): 38 39 __slots__ = ['time', 'priority', 'action', 'argument'] 40 41 def __init__(self, time, priority, action, argument): 42 self.time = time 43 self.priority = priority 44 self.action = action 45 self.argument = argument 46 47 def get_fields(self): 48 return (self.time, self.priority, self.action, self.argument) 49 50 def __eq__(s, o): return (s.time, s.priority) == (o.time, o.priority) 51 def __lt__(s, o): return (s.time, s.priority) < (o.time, o.priority) 52 def __le__(s, o): return (s.time, s.priority) <= (o.time, o.priority) 53 def __gt__(s, o): return (s.time, s.priority) > (o.time, o.priority) 54 def __ge__(s, o): return (s.time, s.priority) >= (o.time, o.priority) 55 56 class scheduler(object): 57 def __init__(self, timefunc, delayfunc): 58 """Initialize a new instance, passing the time and delay 59 functions""" 60 self._queue = [] 61 self.timefunc = timefunc 62 self.delayfunc = delayfunc 63 64 def enterabs(self, time, priority, action, argument): 65 """Enter a new event in the queue at an absolute time. 66 Returns an ID for the event which can be used to remove it, 67 if necessary. 68 """ 69 event = Event(time, priority, action, argument) 70 heapq.heappush(self._queue, event) 71 return event # The ID 72 73 def enter(self, delay, priority, action, argument): 74 """A variant that specifies the time as a relative time. 75 This is actually the more commonly used interface. 76 """ 77 time = self.timefunc() + delay 78 return self.enterabs(time, priority, action, argument) 79 80 def cancel(self, event): 81 """Remove an event from the queue. 82 This must be presented the ID as returned by enter(). 83 If the event is not in the queue, this raises ValueError. 84 """ 85 self._queue.remove(event) 86 heapq.heapify(self._queue) 87 88 def empty(self): 89 """Check whether the queue is empty.""" 90 return not self._queue 91 92 def run(self): 93 """Execute events until the queue is empty. 94 When there is a positive delay until the first event, the 95 delay function is called and the event is left in the queue; 96 otherwise, the event is removed from the queue and executed 97 (its action function is called, passing it the argument). If 98 the delay function returns prematurely, it is simply 99 restarted. 100 It is legal for both the delay function and the action 101 function to modify the queue or to raise an exception; 102 exceptions are not caught but the scheduler's state remains 103 well-defined so run() may be called again. 104 A questionable hack is added to allow other threads to run: 105 just after an event is executed, a delay of 0 is executed, to 106 avoid monopolizing the CPU when other threads are also 107 runnable. 108 """ 109 # localize variable access to minimize overhead 110 # and to improve thread safety 111 q = self._queue 112 delayfunc = self.delayfunc 113 timefunc = self.timefunc 114 pop = heapq.heappop 115 while q: 116 # TODO: modified part of grumpy version. 117 checked_event = q[0] 118 time, priority, action, argument = checked_event.get_fields() 119 now = timefunc() 120 if now < time: 121 delayfunc(time - now) 122 else: 123 event = pop(q) 124 # Verify that the event was not removed or altered 125 # by another thread after we last looked at q[0]. 126 if event is checked_event: 127 action(*argument) 128 delayfunc(0) # Let other threads run 129 else: 130 heapq.heappush(q, event) 131 132 @property 133 def queue(self): 134 """An ordered list of upcoming events. 135 Events are named tuples with fields for: 136 time, priority, action, arguments 137 """ 138 # Use heapq to sort the queue rather than using 'sorted(self._queue)'. 139 # With heapq, two events scheduled at the same time will show in 140 # the actual order they would be retrieved. 141 events = self._queue[:] 142 return map(heapq.heappop, [events]*len(events))