'How can I let a while loop pause for a specified time (datetime)?
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?
Solution 1:[1]
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))
Solution 2:[2]
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?
Solution 3:[3]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Barmar |
| Solution 2 | alecbeau |
| Solution 3 |
