How to launch a function at regular time intervals ?

Grant Edwards invalid at invalid
Thu Aug 13 15:24:07 CEST 2009

On 2009-08-13, Dave Angel <davea at> wrote:

> I'm assuming you want to call it every time_interval seconds, on 
> average, with a little jitter allowed on each call, but keeping correct 
> long term.  In other words, if one call is a little late, you want the 
> next one to still happen as close to on-time as possible.
> The general outline is something like (untested):
> times_called = 0           #number of times function has been called
> start_time = now
> while True:
>      elapsed = now - start_time
>      int_elapsed = int(elapsed/time_interval)
>      for times_called in range(times_called, int_elapsed):
>                     call_the_function()
>      sleep(time_interval/10)           #this might give us 10% jitter, which is usually fine

I don't understand the reasoning behind the above loop --
specifically the sleeping of smaller intervals than needed.

Why not something like this:

    interval = 5.0  # interval in seconds
    next = time.time()

    while True:
        now = time.time()
        if now < next:      
        print "call_the_function()"
        next += interval

That will be accurate over the long term with minimal jitter.


More information about the Python-list mailing list