[英]Timer cannot restart after it is being stopped in Python
I am using Python 2.7. 我使用的是Python 2.7。 I have a timer that keeps repeating a timer callback action until it has been stopped.
我有一个计时器,它一直重复计时器回调操作,直到它被停止。 It uses a Timer object.
它使用Timer对象。 The problem is that after it has been stopped, it cannot be restarted.
问题是在它停止后,它无法重新启动。 The Timer object code is as follows;
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()
To start the timer, the code below is run; 要启动计时器,请运行以下代码;
repeat_timer = RepeatingTimer(interval_timer_sec, timer_function, arg1, arg2)
repeat_timer.start()
To stop the timer, the code is; 要停止计时器,代码是;
repeat_timer.stop()
After it is stopped, I tried to restart the timer by calling repeat_timer.start()
but the timer is unable to start. 停止后,我尝试通过调用
repeat_timer.start()
重新启动计时器,但计时器无法启动。 How can the timer be made to restart after it has been stopped? 定时器如何在停止后重新启动?
Thank you. 谢谢。
Here is a corrected version: 这是一个更正版本:
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()
Example Run: 示例运行:
$ python -i foo.py
>>> Hello World!
>>> Hello World!
>>> t.cancel()
The reason your timer is not restarting is because you never reset self.interval
to True
before trying to restart the timer. 您的计时器未重新启动的原因是您在尝试重新启动计时器之前从未将
self.interval
重置为True
。 However, if that's the only change you make, you will find your timer is vulnerable to a race condition that will result in more than one timer running concurrently. 但是,如果这是您所做的唯一更改,您会发现您的计时器容易受到竞争条件的影响,这将导致同时运行多个计时器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.