a generally useful event scheduler class each instance of this class manages its own queue no multithreading is implied you are supposed to hack that yourself or use a single instance per application each instance is parametrized with two functions one that is supposed to return the current time one that is supposed to implement a delay you can implement realtime scheduling by substituting time and sleep from builtin module time or you can implement simulated time by writing your own functions this can also be used to integrate scheduling with stdwin events the delay function is allowed to modify the queue time can be expressed as integers or floating point numbers as long as it is consistent events are specified by tuples time priority action argument kwargs as in unix lower priority numbers mean higher priority in this way the queue can be maintained as a priority queue execution of the event means calling the action function passing it the argument sequence in argument remember that in python multiple function arguments are be packed in a sequence and keyword parameters in kwargs the action function may be an instance method so it has another way to reference private data besides global variables initialize a new instance passing the time and delay functions self queue self lock threading rlock self timefunc timefunc self delayfunc delayfunc self sequencegenerator count def enterabsself time priority action argument kwargssentinel if kwargs is sentinel kwargs with self lock event eventtime priority nextself sequencegenerator action argument kwargs heapq heappushself queue event return event the id def enterself delay priority action argument kwargssentinel time self timefunc delay return self enterabstime priority action argument kwargs def cancelself event with self lock self queue removeevent heapq heapifyself queue def emptyself execute events until the queue is empty if blocking is false executes the scheduled events due to expire soonest if any and then return the deadline of the next scheduled call in the scheduler when there is a positive delay until the first event the delay function is called and the event is left in the queue otherwise the event is removed from the queue and executed its action function is called passing it the argument if the delay function returns prematurely it is simply restarted it is legal for both the delay function and the action function to modify the queue or to raise an exception exceptions are not caught but the scheduler s state remains welldefined so run may be called again a questionable hack is added to allow other threads to run just after an event is executed a delay of 0 is executed to avoid monopolizing the cpu when other threads are also runnable localize variable access to minimize overhead and to improve thread safety an ordered list of upcoming events events are named tuples with fields for time priority action arguments kwargs use heapq to sort the queue rather than using sortedself queue with heapq two events scheduled at the same time will show in the actual order they would be retrieved numeric type compatible with the return value of the timefunc function passed to the constructor events scheduled for the same time will be executed in the order of their priority a continually increasing sequence number that separates events if time and priority are equal executing the event means executing action argument kwargs argument is a sequence holding the positional arguments for the action kwargs is a dictionary holding the keyword arguments for the action initialize a new instance passing the time and delay functions enter a new event in the queue at an absolute time returns an id for the event which can be used to remove it if necessary the id a variant that specifies the time as a relative time this is actually the more commonly used interface remove an event from the queue this must be presented the id as returned by enter if the event is not in the queue this raises valueerror check whether the queue is empty execute events until the queue is empty if blocking is false executes the scheduled events due to expire soonest if any and then return the deadline of the next scheduled call in the scheduler when there is a positive delay until the first event the delay function is called and the event is left in the queue otherwise the event is removed from the queue and executed its action function is called passing it the argument if the delay function returns prematurely it is simply restarted it is legal for both the delay function and the action function to modify the queue or to raise an exception exceptions are not caught but the scheduler s state remains well defined so run may be called again a questionable hack is added to allow other threads to run just after an event is executed a delay of 0 is executed to avoid monopolizing the cpu when other threads are also runnable localize variable access to minimize overhead and to improve thread safety let other threads run an ordered list of upcoming events events are named tuples with fields for time priority action arguments kwargs 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
import time
import heapq
from collections import namedtuple
from itertools import count
import threading
from time import monotonic as _time

__all__ = ["scheduler"]

Event = namedtuple('Event', 'time, priority, sequence, action, argument, kwargs')
Event.time.__doc__ = ()
Event.priority.__doc__ = ()
Event.sequence.__doc__ = ()
Event.action.__doc__ = ()
Event.argument.__doc__ = ()
Event.kwargs.__doc__ = ()

_sentinel = object()

class scheduler:

    def __init__(self, timefunc=_time, delayfunc=time.sleep):
        
        self._queue = []
        self._lock = threading.RLock()
        self.timefunc = timefunc
        self.delayfunc = delayfunc
        self._sequence_generator = count()

    def enterabs(self, time, priority, action, argument=(), kwargs=_sentinel):
        
        if kwargs is _sentinel:
            kwargs = {}

        with self._lock:
            event = Event(time, priority, next(self._sequence_generator),
                          action, argument, kwargs)
            heapq.heappush(self._queue, event)
        return event 

    def enter(self, delay, priority, action, argument=(), kwargs=_sentinel):
        
        time = self.timefunc() + delay
        return self.enterabs(time, priority, action, argument, kwargs)

    def cancel(self, event):
        
        with self._lock:
            self._queue.remove(event)
            heapq.heapify(self._queue)

    def empty(self):
        
        with self._lock:
            return not self._queue

    def run(self, blocking=True):
        
        
        
        lock = self._lock
        q = self._queue
        delayfunc = self.delayfunc
        timefunc = self.timefunc
        pop = heapq.heappop
        while True:
            with lock:
                if not q:
                    break
                (time, priority, sequence, action,
                 argument, kwargs) = q[0]
                now = timefunc()
                if time > now:
                    delay = True
                else:
                    delay = False
                    pop(q)
            if delay:
                if not blocking:
                    return time - now
                delayfunc(time - now)
            else:
                action(*argument, **kwargs)
                delayfunc(0)   

    @property
    def queue(self):
        
        
        
        
        with self._lock:
            events = self._queue[:]
        return list(map(heapq.heappop, [events]*len(events)))