How to launch a function at regular time intervals ?
Grant Edwards
invalid at invalid
Thu Aug 13 12:40:06 EDT 2009
On 2009-08-13, Dave Angel <davea at ieee.org> wrote:
> Grant Edwards wrote:
>> On 2009-08-13, Dave Angel <davea at ieee.org> wrote:
>>> 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.
I guess I always use a separate thread for cases like that.
> 2) If (occasionally) the function takes longer than the
> specified interval time, my approach does catch-up calls so
> the average remains the same.
I'm still confused -- doesn't mine do that as well?
--
Grant Edwards grante Yow! Are you the
at self-frying president?
visi.com
More information about the Python-list
mailing list