Skip to content Skip to sidebar Skip to footer

With Python: Intervals At X:00 Repeat

How do I sched a repeat timer for 5 min intervals. Which fire at 00 seconds, then repeat at 00. Ok, not hard real-time but as close as possible with sys lags. Trying to avoid a bui

Solution 1:

I don't know how to do it any more accurately than with threading.Timer. It's "one-shot", but that just means the function you schedule that way must immediately re-schedule itself for another 300 seconds later, first thing. (You can add accuracy by measuring the exact time with time.time each time and varying the next scheduling delay accordingly).

Solution 2:

Try and compare the time printouts of these two code samples:

Code Sample 1

import time
delay = 5whileTrue:
    now = time.time()
    print time.strftime("%H:%M:%S", time.localtime(now))

    # As you will observe, this will take about 2 seconds,# making the loop iterate every 5 + 2 seconds or so.## repeat 5000 timesfor i inrange(5000):
        sum(range(10000))

    # This will sleep for 5 more seconds
    time.sleep(delay)

Code Sample 2

import time
delay = 5whileTrue:
    now = time.time()
    print time.strftime("%H:%M:%S", time.localtime(now))

    # As you will observe, this will take about 2 seconds,# but the loop will iterate every 5 seconds because code # execution time was accounted for.## repeat 5000 timesfor i inrange(5000):
        sum(range(10000))

    # This will sleep for as long as it takes to get to the# next 5-second mark
    time.sleep(delay - (time.time() - now))

Post a Comment for "With Python: Intervals At X:00 Repeat"