我正在使用 Python 2.7。我有一个计时器,它会不断重复计时器回调操作,直到它停止为止。它使用一个 Timer 对象。问题是停止后无法重新启动。 Timer对象代码如下;
from threading import Timer
class RepeatingTimer(object):
def __init__(self,interval, function, *args, **kwargs):
super(RepeatingTimer, self).__init__()
self.args = args
self.kwargs = kwargs
self.function = function
self.interval = interval
def start(self):
self.callback()
def stop(self):
self.interval = False
def callback(self):
if self.interval:
self.function(*self.args, **self.kwargs)
Timer(self.interval, self.callback, ).start()
要启动计时器,请运行以下代码;
repeat_timer = RepeatingTimer(interval_timer_sec, timer_function, arg1, arg2)
repeat_timer.start()
要停止定时器,代码是;
repeat_timer.stop()
停止后,我尝试通过调用 repeat_timer.start()
重新启动计时器,但计时器无法启动。如何让计时器在停止后重新启动?
谢谢。
最佳答案
这是更正后的版本:
from __future__ import print_function
from threading import Timer
def hello():
print("Hello World!")
class RepeatingTimer(object):
def __init__(self, interval, f, *args, **kwargs):
self.interval = interval
self.f = f
self.args = args
self.kwargs = kwargs
self.timer = None
def callback(self):
self.f(*self.args, **self.kwargs)
self.start()
def cancel(self):
self.timer.cancel()
def start(self):
self.timer = Timer(self.interval, self.callback)
self.timer.start()
t = RepeatingTimer(3, hello)
t.start()
示例运行:
$ python -i foo.py
>>> Hello World!
>>> Hello World!
>>> t.cancel()
关于python - 定时器在 Python 中停止后无法重新启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24072765/