How to launch a function at regular time intervals ?

Dave Angel davea at ieee.org
Thu Aug 13 11:52:45 EDT 2009


Grant Edwards wrote:
> On 2009-08-13, Dave Angel <davea at ieee.org> 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:      
>             time.sleep(now-next)
>         print "call_the_function()"
>         next += interval
>
> That will be accurate over the long term with minimal jitter.
>
>       
>
>   
Two reasons I didn't take an approach like that one.

1) I frequently need to do something else while waiting, so I tend to do 
multiple smaller sleeps.  As long as each sleep is at least 100ms, the 
overhead cost is pretty small.
2) If (occasionally) the function takes longer than the specified 
interval time, my approach does catch-up calls so the average remains 
the same.

My loop was only a rough outline, and if neither of these considerations 
applies, yours is much nicer.

DaveA



More information about the Python-list mailing list