Timer

Anand Pillai pythonguy at Hotpop.com
Mon Oct 27 15:42:27 EST 2003


Python standard library offers a 'Timer' class as part
of its threading library. 

The documentation should be reachable at 
http://www.python.org/doc/current/lib/timer-objects.html

It is easy to create your own timer objects by using 
python threads.

Here is a sample code for the same. It is a working
code, and creates a custom timer class with a maximum
timeout, which calls the function again and again until
it times out. It is different from the standard timer
which calls its target function just once.

----------------<snip>-----<snip>--------------------
from threading import Thread
import time

class ModifiedTimer(Thread):

    def __init__(self, interval, maxtime, target):
        self.__interval = interval
        self.__maxtime = maxtime
        self.__tottime = 0.0
        self.__target = target
        self.__flag = 0
        Thread.__init__(self, None, 'mytimer', None)
        
    def run(self):

        while self.__flag==0:
            time.sleep(self.__interval)
            self.__target()
            self.__tottime += self.__interval

            if self.__tottime >= self.__maxtime:
                print 'Timing out...'
                self.end()
            
    def end(self):
        self.__flag=1
        
class MyTimer:

    def __init__(self):
        self.__interval = 5.0
        
    def __timerfunc(self):
        print 'Hello, this is the timer function!'

    def make_timer(self, interval):
        self.__interval = interval
        self.__timer = ModifiedTimer(self.__interval, 60.0, self.__timerfunc)
        self.__timer.start()

if __name__=="__main__":
    t=MyTimer()
    t.make_timer(10.0)
    
------------------<snip>-----------<snip>---------------


HTH

-Anand Pillai


Bob Gailer <bgailer at alum.rpi.edu> wrote in message news:<mailman.136.1067267376.702.python-list at python.org>...
> At 09:21 PM 10/26/2003, Derek Fountain wrote:
> 
> >Does Python have a timer mechanism? i.e. an "after 500 milliseconds, run
> >this bit of code" sort of thing?
> 
> Check out the sched and time modules.
> 
> Bob Gailer
> bgailer at alum.rpi.edu
> 303 442 2625
> 
> --




More information about the Python-list mailing list