Speed ​​limits infinite while loop in Python

If I have an infinite loop while, how can I start the loop with the next iteration every 10 minutes from the start of the loop iteration?

If the first iteration starts at 1:00 and ends at 1:09 in the morning, the next iteration should be done at 1:10, and not wait another 10 minutes (as in the code snippet below). If the iteration of the cycle took more than 10 minutes to start, the next iteration should start immediately and begin to count down 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
+4
source share
1 answer

Remember the start time, calculate the sleep time using this.

while True:
    start = time.time()
    some_long_process()
    end = time.time()
    remain = start + 10*60 - end
    if remain > 0:
        time.sleep(remain)
+8
source

Source: https://habr.com/ru/post/1527817/


All Articles