long-run repeatly timer?

Qiangning Hong hongqn at gmail.com
Fri Nov 12 04:32:50 EST 2004


At first I showed my test code:

     import threading
     def timer_handler():
         threading.Timer(10, timer_handler).start()
         do_something()
     timer_handler()

But it's tick interval is slightly more than 10 seconds because of 
creating of Timer object.  John Hoffman shows his code:

    from time import time, sleep

    t = time()
    while True:
        do_something()
        t += 10
        sleep(t-time())

His code can call do_something() exactly every 10 seconds, but if the 
system time is changed by GPS module, the counter will behave abnormal: 
if the system clock is adjusted backward, the timer will pause for some 
time; if the system clock is adjusted foreward, the timer will stop forever.

Jonh A Meinel provides a modified version of above code:

     t = time()
     while True:
         do_something()
         t += 10
         now = time()
         interval = t - now
         # If the time skews enough that we are outside of are 10 second
         # interval, switch back to a 10 second pulse
         if interval < 0 or interval > 10:
            interval = 10
             t = now + interval
         sleep(interval)

It does avoid the long waiting and forever-stopping, but it can not 
guaratee the tick interval as 10 seconds.


Qiangning Hong wrote:
> I asked this question on comp.python.wxpython using the subject "a 
> wx.Timer like timer without wx package?" and David Fraser there 
> suggested me to ask here for a more general solution.
> 
> I am implementing a long-run sample-and-record system.  It collects data 
> from a PCI card every 10 seconds, saves the data (timestamped with the 
> current system time) in the hard disk, and shows them on the screen. 
> There is also a GPS receiver module exists on the system, which correct 
> the system time (and the hardware time) when it drifts away too much, 
> however, I can not access the source code of this module.
> 
> The system requires the average sample rate is 6 times per minute to 
> analysis.  If the OS clock runs too fast or too slow, we can get the 
> infomation by the GPS module's log file, and then correct the analysised 
> result with that infomation.
> 
> So, wo need the counter (a repeatly timer for collecting data) to meet 
> these requirements:
> 
> 1. fires 6 times per minute, or to say, fires 60*24*360 times per 60 days.
> 2. will not be affected by the change of system time, foreward or backward.
> 3. no need for external hardware device, of cource.
> 4. not depend on any GUI package for it's a console based app.
> 5. works on a Windows mechine, cross-platform solution is better.
> 
> How can I implement such a timer?  Thanks in advance.
> 




More information about the Python-list mailing list