计时器在 Python 中停止后无法重新启动 [英] Timer cannot restart after it is being stopped in Python
本文介绍了计时器在 Python 中停止后无法重新启动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用的是 Python 2.7.我有一个计时器,它不断重复计时器回调动作,直到它停止.它使用一个 Timer 对象.问题是它被停止后,无法重新启动.Timer对象代码如下;
I am using Python 2.7. I have a timer that keeps repeating a timer callback action until it has been stopped. It uses a Timer object. The problem is that after it has been stopped, it cannot be restarted. The Timer object code is as follows;
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()
要启动定时器,运行下面的代码;
To start the timer, the code below is run;
repeat_timer = RepeatingTimer(interval_timer_sec, timer_function, arg1, arg2)
repeat_timer.start()
停止定时器,代码为;
repeat_timer.stop()
停止后,我尝试通过调用 repeat_timer.start()
重新启动计时器,但计时器无法启动.定时器停止后如何重新启动?
After it is stopped, I tried to restart the timer by calling repeat_timer.start()
but the timer is unable to start. How can the timer be made to restart after it has been stopped?
谢谢.
推荐答案
这是一个更正的版本:
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 中停止后无法重新启动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文