better scheduler with correct sleep times

sokol tvrtko.sokolovski at gmail.com
Sun Oct 19 15:57:10 EDT 2008


On Oct 19, 6:25 pm, Scott David Daniels <Scott.Dani... at Acm.Org> wrote:
> 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, {}))

I see what you did there. You are keeping the queue empty
so you get notified for free, while I introduced a new
threading Condition to detect insertions.
All that is missing in your version is to put back all
pending tasks when somebody sends the stop (None) request.

Shouldn't sched module do something similar?

Tvrtko



More information about the Python-list mailing list