python - 定时器在 Python 中停止后无法重新启动

标签 python python-2.7 timer python-multithreading

我正在使用 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/

相关文章:

python - 使用用户输入打印数学: Can't convert float to str implicitly

python - Argparse:文件中的默认值

python - "\n"会立即转换为 python 中的换行符吗?

python-2.7 - Scikit-Learn One-hot-encode 在训练/测试拆分之前或之后

xcode - 为什么我的计时器在 Swift 中不倒计时到 0?

python - 使用 pyparsing 解析嵌套结构

python - 如何从嵌套 JSON 中获取扁平 JSON?

python - 访问值 boto3 字典响应

c++ - POSIX 计时器可以安全地修改 C++ STL 对象吗?

windows-phone-7 - 在给定延迟后执行方法的简单方法?