Back to index

python3.2  3.2.2
sched.py
Go to the documentation of this file.
00001 """A generally useful event scheduler class.
00002 
00003 Each instance of this class manages its own queue.
00004 No multi-threading is implied; you are supposed to hack that
00005 yourself, or use a single instance per application.
00006 
00007 Each instance is parametrized with two functions, one that is
00008 supposed to return the current time, one that is supposed to
00009 implement a delay.  You can implement real-time scheduling by
00010 substituting time and sleep from built-in module time, or you can
00011 implement simulated time by writing your own functions.  This can
00012 also be used to integrate scheduling with STDWIN events; the delay
00013 function is allowed to modify the queue.  Time can be expressed as
00014 integers or floating point numbers, as long as it is consistent.
00015 
00016 Events are specified by tuples (time, priority, action, argument).
00017 As in UNIX, lower priority numbers mean higher priority; in this
00018 way the queue can be maintained as a priority queue.  Execution of the
00019 event means calling the action function, passing it the argument
00020 sequence in "argument" (remember that in Python, multiple function
00021 arguments are be packed in a sequence).
00022 The action function may be an instance method so it
00023 has another way to reference private data (besides global variables).
00024 """
00025 
00026 # XXX The timefunc and delayfunc should have been defined as methods
00027 # XXX so you can define new kinds of schedulers using subclassing
00028 # XXX instead of having to define a module or class just to hold
00029 # XXX the global state of your particular time and delay functions.
00030 
00031 import heapq
00032 from collections import namedtuple
00033 
00034 __all__ = ["scheduler"]
00035 
00036 class Event(namedtuple('Event', 'time, priority, action, argument')):
00037     def __eq__(s, o): return (s.time, s.priority) == (o.time, o.priority)
00038     def __ne__(s, o): return (s.time, s.priority) != (o.time, o.priority)
00039     def __lt__(s, o): return (s.time, s.priority) <  (o.time, o.priority)
00040     def __le__(s, o): return (s.time, s.priority) <= (o.time, o.priority)
00041     def __gt__(s, o): return (s.time, s.priority) >  (o.time, o.priority)
00042     def __ge__(s, o): return (s.time, s.priority) >= (o.time, o.priority)
00043 
00044 class scheduler:
00045     def __init__(self, timefunc, delayfunc):
00046         """Initialize a new instance, passing the time and delay
00047         functions"""
00048         self._queue = []
00049         self.timefunc = timefunc
00050         self.delayfunc = delayfunc
00051 
00052     def enterabs(self, time, priority, action, argument):
00053         """Enter a new event in the queue at an absolute time.
00054 
00055         Returns an ID for the event which can be used to remove it,
00056         if necessary.
00057 
00058         """
00059         event = Event(time, priority, action, argument)
00060         heapq.heappush(self._queue, event)
00061         return event # The ID
00062 
00063     def enter(self, delay, priority, action, argument):
00064         """A variant that specifies the time as a relative time.
00065 
00066         This is actually the more commonly used interface.
00067 
00068         """
00069         time = self.timefunc() + delay
00070         return self.enterabs(time, priority, action, argument)
00071 
00072     def cancel(self, event):
00073         """Remove an event from the queue.
00074 
00075         This must be presented the ID as returned by enter().
00076         If the event is not in the queue, this raises ValueError.
00077 
00078         """
00079         self._queue.remove(event)
00080         heapq.heapify(self._queue)
00081 
00082     def empty(self):
00083         """Check whether the queue is empty."""
00084         return not self._queue
00085 
00086     def run(self):
00087         """Execute events until the queue is empty.
00088 
00089         When there is a positive delay until the first event, the
00090         delay function is called and the event is left in the queue;
00091         otherwise, the event is removed from the queue and executed
00092         (its action function is called, passing it the argument).  If
00093         the delay function returns prematurely, it is simply
00094         restarted.
00095 
00096         It is legal for both the delay function and the action
00097         function to to modify the queue or to raise an exception;
00098         exceptions are not caught but the scheduler's state remains
00099         well-defined so run() may be called again.
00100 
00101         A questionable hack is added to allow other threads to run:
00102         just after an event is executed, a delay of 0 is executed, to
00103         avoid monopolizing the CPU when other threads are also
00104         runnable.
00105 
00106         """
00107         # localize variable access to minimize overhead
00108         # and to improve thread safety
00109         q = self._queue
00110         delayfunc = self.delayfunc
00111         timefunc = self.timefunc
00112         pop = heapq.heappop
00113         while q:
00114             time, priority, action, argument = checked_event = q[0]
00115             now = timefunc()
00116             if now < time:
00117                 delayfunc(time - now)
00118             else:
00119                 event = pop(q)
00120                 # Verify that the event was not removed or altered
00121                 # by another thread after we last looked at q[0].
00122                 if event is checked_event:
00123                     action(*argument)
00124                     delayfunc(0)   # Let other threads run
00125                 else:
00126                     heapq.heappush(q, event)
00127 
00128     @property
00129     def queue(self):
00130         """An ordered list of upcoming events.
00131 
00132         Events are named tuples with fields for:
00133             time, priority, action, arguments
00134 
00135         """
00136         # Use heapq to sort the queue rather than using 'sorted(self._queue)'.
00137         # With heapq, two events scheduled at the same time will show in
00138         # the actual order they would be retrieved.
00139         events = self._queue[:]
00140         return map(heapq.heappop, [events]*len(events))