Home > Software engineering >  How to run timer every x seconds within a loop without stalling the loop?
How to run timer every x seconds within a loop without stalling the loop?

Time:01-18

i = 0
start = datetime.now()
while True:
    myFunction()
    i  = 1
    print('Elapsed: '   str(datetime.now()-start)   ' | Iteration #'   str(i))

I would like to print the timer information every 10 seconds instead of at every iteration of the loop, but without actually stalling the loop itself, so that myFunction() still does what it needs to do (and the i counter increases subsequently) without waiting 10 seconds.

CodePudding user response:

Use datetime.timedelta to check if enough time passed:

import datetime

i = 0
start = datetime.datetime.now()
last = start

while True:
    my_function()
    i  = 1
    now = datetime.datetime.now()
    if now - last > datetime.timedelta(seconds=10):
        last = now
        print('Elapsed: '   str(now-start)   ' | Iteration #'   str(i))
  •  Tags:  
  • Related