do something in time interval

Hendrik van Rooyen mail at
Thu Oct 9 23:53:03 CEST 2008

Lawrence D'Oliveiro wrote:
>Hendrik van Rooyen wrote:
>>     import time
>>     while True:
>>         end_time = time.time() + 5
>>         while time.time() < end_time:
>>             do_the_in_between_stuff()
>>         do_the_every_five_second_stuff()
>Maybe I'm dense, but ... where do you stop the busy-waiting?

The above is an endless loop, doing something every
five seconds, and something else in the in between times.

I don't think you are dense - its a good point,
leading to the following analysis:

The do_the_in_between_stuff call either takes
less than, or more than, or exactly five
seconds to do.

In the unlikely exact case, there is no problem, we
have a synchronous machine. (assuming the every five
seconds code takes zero time - else five has to
be diminished to 5 less the time of the periodic
routine, but the argument stays the same)

If it takes more than five seconds, we fail in our
endeavour to do something every five seconds,
and we need threads or interrupts or something else
more advanced to get some apparent simultaneity.

If it takes less than five seconds, we will enter it
more than once.  I wrote the above under the twin assumptions
that multiple entry does not matter, and that the routine
is short enough in time that the overrun error at the end
does not significantly change the timing of the five second
interval call. If it perversely takes say 4 seconds to do
the in between stuff, the above code will do the five second
stuff at intervals of eight seconds or so. - Conversely, if the
in between code takes a millisec, then we will be almost

Now if multiple entry does matter, and it has to be done
only once in between calls to the five second stuff,
then it properly belongs with the five second stuff,
and we are back to sleeping for
time.sleep(5 - time_to_do_the_work) to get a call every
five seconds.  Obviously, if time_to_do_the_work is
bigger than 5, then you can't get there from here.

And these, as far as I can see, are the only alternatives.

- Hendrik

More information about the Python-list mailing list