better scheduler with correct sleep times

sokol tvrtko.sokolovski at gmail.com
Mon Oct 20 09:57:32 EDT 2008


On Oct 20, 1:50 pm, Lie <Lie.1... at gmail.com> wrote:
> On Oct 19, 4:01 am, sokol <tvrtko.sokolov... at gmail.com> wrote:
> > > > I started googling for scheduler and found one in standard library
> > > > but ih has the same code as mine (it calls the  functions in the
> > > > right order and my doesn't, but it still waits too long).
> > > > The other schedulers from web are dealing with
> > > > repeating tasks and such.
>
> > > I believe you're looking for the 'sched' module:http://www.python.org/doc/2.5.2/lib/module-sched.html
>
> > The sched module behaves just like mine version because
> > it uses almost the same code. My observations include the
> > sched module as well. Check it's source code. It is flawed:
> > it calls the sleep method and while it sleeps (presumably
> > for a long time) all newly scheduled events are on hold.
> > See my example in original post.
>
> > My code solves this problem (or so it looks to me right now).
>
> Alternatively, if you're only handling Timers, you could use an event
> loop that would check a list of timers and check their expiry time,
> and execute the appropriate callback when the timer expired.

And that is what I'm doing. The trick is to do it correctly while:

1. Not using the processor time in useless loops and checks
   -> use sleep()

2. Sleep just as much as it is needed and not too much
   -> wake from sleep if there are new tasks since new tasks
   could be scheduled for some earlier point in time.

My solution was: introduce "new_task" event and sleep on it with
desired timeout. If new tasks arrive I will be awaken before the
timeout and get a chance to reexamine if I need to sleep less
than before.

Scott's solution was: keep the queue empty so you get awaken
automatically when new tasks are queued. Much simpler.

Also, threading is quite necessary in my case: this "event loop"
is not the main loop of the program as is found in GUI applications,
but rather a plain old scheduler which runs some tasks concurrently
to the main thread of execution.

What was a surprise to me was that python sched.py makes the same
mistake as I did in my first version.

Tvrtko



More information about the Python-list mailing list