Question

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 build up in lags and get near 00.

Lang: Python, OS: WinXP x64

System has 25ms resolution.

Any code would be helpful, tia

Was it helpful?

Solution

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

OTHER TIPS

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

Code Sample 1

import time
delay = 5

while True:
    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 times
    for i in range(5000):
        sum(range(10000))

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

Code Sample 2

import time
delay = 5

while True:
    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 times
    for i in range(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))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top