better scheduler with correct sleep times

Scott David Daniels Scott.Daniels at Acm.Org
Sun Oct 19 12:25:06 EDT 2008


qvx wrote:
> I need a scheduler which can delay execution of a
> function for certain period of time.
> My attempt was something like this:  ... <<<code>>>
> Is there a better way or some library that does that?

The trick is to use Queue's timeout argument to interrupt your sleep
when new requests come in.


def time_server(commands):
     '''Process all scheduled operations that arrive on queue commands'''
     pending = []
     while True:
         now = time.time()
         while pending and pending[0][0] <= now:
             when, function, args, kwargs = heapq.heappop(pending)
             function(*args, **kwargs)
         try:
             command = commands.get(timeout=pending[0][0] - now
                                            if pending else None)
         except Queue.Empty:
             pass
         else:
             if command is None:
                 break
             heapq.heappush(pending, command)

queue = Queue.Queue()
thread.thread.start_new_thread(queue)
queue.put((time.time() + dt, callable, args, {}))
...

--Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list