Instandplay
Instandplay

Reputation: 33

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?

Upvotes: 0

Views: 339

Answers (2)

Barmar
Barmar

Reputation: 780994

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))

Upvotes: 1

alecbeau
alecbeau

Reputation: 41

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?

Upvotes: 0

Related Questions