Home > other >  How can I let a while loop pause for a specified time (datetime)?
How can I let a while loop pause for a specified time (datetime)?

Time:02-26

I would like to let a while loop run, the stuff thats happening inside takes about 2 seconds to complete (it varies a small amount), so if I use time.sleep(60 or 58) it would still shift slightly. So what I would like to do is that the while loop starts for example at 16:00:00 (because I click run) and does its stuff, waits and then starts again at 16:01:00, so a minute later and so on. How can I do that? Because I just can´t seem to find an answer to that. Thanks in advance

CodePudding user response:

Measure the time taken by the operation. Then subtract that from your loop period to get the amount of time to sleep.

import time

while True:
    start = time.time()
    # do your thing
    time.sleep(60 - (time.time() - start))

CodePudding user response:

Where are you putting time.sleep() in your code? Have you tried putting it at the end of the while loop when all of the processing is complete?

CodePudding user response:

Calling the stop function will stop your while loop for the amount you pass. This works I tested it

def stop(t):
    running = False
    time.sleep(t)
    running = True

while running:
    # Do something
  • Related