• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1"""A generally useful event scheduler class.
2
3Each 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.
6
7Each 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, kwargs).
17As in UNIX, lower priority numbers mean higher priority; in this
18way the queue can be maintained as a priority queue.  Execution of the
19event 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) and keyword parameters in "kwargs".
22The action function may be an instance method so it
23has another way to reference private data (besides global variables).
24"""
25
26import time
27import heapq
28from collections import namedtuple
29from itertools import count
30import threading
31from time import monotonic as _time
32
33__all__ = ["scheduler"]
34
35Event = namedtuple('Event', 'time, priority, sequence, action, argument, kwargs')
36Event.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.''')
40Event.sequence.__doc__ = ('''A continually increasing sequence number that
41    separates events if time and priority are equal.''')
42Event.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
49_sentinel = object()
50
51class scheduler:
52
53    def __init__(self, timefunc=_time, delayfunc=time.sleep):
54        """Initialize a new instance, passing the time and delay
55        functions"""
56        self._queue = []
57        self._lock = threading.RLock()
58        self.timefunc = timefunc
59        self.delayfunc = delayfunc
60        self._sequence_generator = count()
61
62    def enterabs(self, time, priority, action, argument=(), kwargs=_sentinel):
63        """Enter a new event in the queue at an absolute time.
64
65        Returns an ID for the event which can be used to remove it,
66        if necessary.
67
68        """
69        if kwargs is _sentinel:
70            kwargs = {}
71
72        with self._lock:
73            event = Event(time, priority, next(self._sequence_generator),
74                          action, argument, kwargs)
75            heapq.heappush(self._queue, event)
76        return event # The ID
77
78    def enter(self, delay, priority, action, argument=(), kwargs=_sentinel):
79        """A variant that specifies the time as a relative time.
80
81        This is actually the more commonly used interface.
82
83        """
84        time = self.timefunc() + delay
85        return self.enterabs(time, priority, action, argument, kwargs)
86
87    def cancel(self, event):
88        """Remove an event from the queue.
89
90        This must be presented the ID as returned by enter().
91        If the event is not in the queue, this raises ValueError.
92
93        """
94        with self._lock:
95            self._queue.remove(event)
96            heapq.heapify(self._queue)
97
98    def empty(self):
99        """Check whether the queue is empty."""
100        with self._lock:
101            return not self._queue
102
103    def run(self, blocking=True):
104        """Execute events until the queue is empty.
105        If blocking is False executes the scheduled events due to
106        expire soonest (if any) and then return the deadline of the
107        next scheduled call in the scheduler.
108
109        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.
115
116        It is legal for both the delay function and the action
117        function to modify the queue or to raise an exception;
118        exceptions are not caught but the scheduler's state remains
119        well-defined so run() may be called again.
120
121        A questionable hack is added to allow other threads to run:
122        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        """
127        # localize variable access to minimize overhead
128        # and to improve thread safety
129        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
138                (time, priority, sequence, action,
139                 argument, kwargs) = q[0]
140                now = timefunc()
141                if time > now:
142                    delay = True
143                else:
144                    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
153
154    @property
155    def queue(self):
156        """An ordered list of upcoming events.
157
158        Events are named tuples with fields for:
159            time, priority, action, arguments, kwargs
160
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.
165        with self._lock:
166            events = self._queue[:]
167        return list(map(heapq.heappop, [events]*len(events)))
168