在Python中停止后,Timer无法重新启动

时间:2014-06-06 01:23:12

标签: 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()重新启动计时器,但计时器无法启动。定时器如何在停止后重新启动?

谢谢。

2 个答案:

答案 0 :(得分:5)

以下是更正后的版本:

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()

答案 1 :(得分:1)

您的计时器未重新启动的原因是您在尝试重新启动计时器之前从未将self.interval重置为True。但是,如果这是您所做的唯一更改,您会发现您的计时器容易受到竞争条件的影响,这将导致同时运行多个计时器。

相关问题