David wrote:
Hi all, I'm trying to launch a function at regular time intervals but
cannot find the way to do it. Here is the code I wrote (time_interval
is a user defined variable in seconds):
while(1)
timestamp=datetime.now()
timestamp_seconds=timestamp.hour*3600+timestamp.minute*60+timestamp.second
if timestamp_seconds % time_interval == 0: ****Call Function****
This does not work because during the second at which the condition
holds true, there is time to call the function several times. Since I
want to have this function called only once every x seconds, I tried
to add the following condition:
if timestamp_seconds % time_interval ==0 & timestamp.microsecond == 0
But it seems this second condition hardly ever happens (i.e. the
timestamp variable is not updated every microsecond, therefore it can
be 9998 then jump directly to 0003 for instance).
Has anyone run into a similar problem (and solved it) ?
Thanks for your help
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
DaveA
--
http://mail.python.org/mailman/listinfo/python-list