do something in time interval

Terry Reedy tjreedy at udel.edu
Mon Oct 6 14:43:31 EDT 2008


Petr Jakes wrote:
> I have infinitive loop running script and I would like to check
> something periodically after 5 seconds (minutes, hours...) time period
> (I do not mean time.sleep(5) ). Till now, I have following script, but
> I think there must be something more elegant.
> 
> eventFlag = False
> while 1:
>     time.sleep(0.01)
>     seconds = time.time()
>     if not int(seconds % (5)):
>         if eventFlag:
>             print "5 seconds, hurray"
>             eventFlag = False
>     else:
>         eventFlag = True

The eventFlag is confusing.  Better:

dt = 5 # for instance
event_time = time.time()
while 1:
   #do every loop stuff
   now = time.time()
   if now >= event_time:
     event_time = now + dt
     event()

If you have multiple delayed events, quite possibly each with a 
different or even variable delta, store (future_time,func_to_call) pairs 
in a priority queue (heapq module).

Terry Jan Reedy




More information about the Python-list mailing list