Created
July 28, 2008 01:34
-
-
Save harryxu/2822 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from threading import _Timer | |
class Timer(_Timer): | |
def __init__(self, interval, handler, repeats=0, args=[], kwargs={}): | |
_Timer.__init__(self, interval, self.__invoke, args, kwargs) | |
self.handler = handler | |
self.repeats = repeats | |
self.repeatCount = 0 | |
self.running = False | |
self.started = False | |
def __invoke(self, args=[], kwargs={}): | |
if not self.running: | |
return | |
self.handler(*args, **kwargs) | |
self.repeatCount += 1 | |
self.running = False | |
self.__run() | |
def __run(self): | |
if self.repeats == 0 or \ | |
self.repeatCount < self.repeats and not self.running: | |
self.running = True | |
self.run() | |
elif self.repeatCount >= self.repeats: | |
self.repeatCount = 0 | |
def start(self): | |
if not self.started: | |
self.running = True | |
self.started = True | |
_Timer.start(self) | |
else: | |
self.__run() | |
def stop(self): | |
self.canncel() | |
self.running = False | |
def reset(self): | |
self.repeatCount = 0 | |
self.stop() | |
def restart(self): | |
self.reset() | |
self.start() | |
#--- just test --- | |
def say(): | |
print 'hello world' | |
if __name__ == '__main__': | |
t = Timer(2, say, 3); | |
t.start() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment