Scheduler Objects
-----------------
-:class:`scheduler` instances have the following methods:
+:class:`scheduler` instances have the following methods and attributes:
.. method:: scheduler.enterabs(time, priority, action, argument)
the calling code is responsible for canceling events which are no longer
pertinent.
+.. attribute:: scheduler.queue
+
+ Read-only attribute returning a list of upcoming events in the order they
+ will be run. Each event is shown as a :term:`named tuple` with the
+ following fields: time, priority, action, argument.
# XXX the global state of your particular time and delay functions.
import heapq
+from collections import namedtuple
__all__ = ["scheduler"]
+Event = namedtuple('Event', 'time, priority, action, argument')
+
class scheduler:
def __init__(self, timefunc, delayfunc):
"""Initialize a new instance, passing the time and delay
functions"""
- self.queue = []
+ self._queue = []
self.timefunc = timefunc
self.delayfunc = delayfunc
if necessary.
"""
- event = time, priority, action, argument
- heapq.heappush(self.queue, event)
+ event = Event(time, priority, action, argument)
+ heapq.heappush(self._queue, event)
return event # The ID
def enter(self, delay, priority, action, argument):
If the event is not in the queue, this raises RuntimeError.
"""
- self.queue.remove(event)
- heapq.heapify(self.queue)
+ self._queue.remove(event)
+ heapq.heapify(self._queue)
def empty(self):
"""Check whether the queue is empty."""
- return not self.queue
+ return not self._queue
def run(self):
"""Execute events until the queue is empty.
"""
# localize variable access to minimize overhead
# and to improve thread safety
- q = self.queue
+ q = self._queue
delayfunc = self.delayfunc
timefunc = self.timefunc
pop = heapq.heappop
delayfunc(0) # Let other threads run
else:
heapq.heappush(event)
+
+ @property
+ def queue(self):
+ """An ordered list of upcoming events.
+
+ Events are named tuples with fields for:
+ time, priority, action, arguments
+
+ """
+ # Use heapq to sort the queue rather than using 'sorted(self._queue)'.
+ # With heapq, two events scheduled at the same time will show in
+ # the actual order they would be retrieved.
+ events = self._queue[:]
+ return map(heapq.heappop, [events]*len(events))