views:

78

answers:

2

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

+2  A: 

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

Alex Martelli
A: 

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))
Kit
the delay lag bulid after every fire. how to correct?
Did you run the code? I modified my code samples so that you can see the time printouts. I used a 5-second delay to make it easier to demonstrate.
Kit
Trying it, TIAHow I kill it? How do get it to start at 00:05:00.0000?How do check with microseconds. this is so I can see "below a second",
2nd method worked better, TIAAlso, on win x64, see pthyonw.exe running, a couple of them, do know how to identify the correct Pythonw.exe to kill?
To see fractions of a second, add this line after `now = time.time()`: `print now`. To make it start at `5:00.0000`, do a `time.sleep(5*60)` right after `import time`. To identify the correct `pythonw.exe`, that would be a topic for another question. Cheers!
Kit
"To make it start at 5:00.0000, do a time.sleep(5*60) right after import time." didnt work....Idea now as float without fraction....how do i kill this?
this method keeps crashing