Reputation: 63599
If I have a infinite while
loop, how can I have the loop run the next iteration every 10 minutes from the start of the loop iteration?
If the first iteration starts at 1:00am and finishes at 1:09am, the next iteration should run at 1:10am instead of waiting for another 10 minutes (like in the code snippet below). If the loop iteration took more than 10 minutes to run, the next iteration should run immediately and start the countdown of the next 10 minutes.
while(True):
someLongProcess() # takes 5-15 minutes
time.sleep(10*60)
Example
Loop 1: Starts 1:00am, ends 1:09am
Loop 2: Start 1:10am, ends 1:25am # ends 5 minutes later
Loop 3: Starts 1:25am, ends 1:30am # ends 5 minutes earlier
Loop 4: Starts 1:35am, ends 1:45am
Upvotes: 7
Views: 3963
Reputation: 368914
Remember the start time, calculate sleep time using that.
while True:
start = time.time()
some_long_process()
end = time.time()
remain = start + 10*60 - end
if remain > 0:
time.sleep(remain)
Upvotes: 12