python中的可重置计时器重复,直到被取消

时间:2013-03-27 04:31:06

标签: python timer reset

我已复制此网址http://code.activestate.com/recipes/577407-resettable-timer-class-a-little-enhancement-from-p/

中的代码

要创建一个可重置的计时器,它可以很好地工作但是一旦完成就结束了。我想重新开始,但我是新手,无法理解如何做到这一点。

我厌倦了在行后面的run()函数底部创建一个新的实例:

print "Time: %s - timer finished!" % time.asctime()

但是python似乎不喜欢它。

Eddy Jacob创建的复制粘贴代码是:

from threading import Thread, Event, Timer
import time

def TimerReset(*args, **kwargs):
    """ Global function for Timer """
    return _TimerReset(*args, **kwargs)


class _TimerReset(Thread):
    """Call a function after a specified number of seconds:

    t = TimerReset(30.0, f, args=[], kwargs={})
    t.start()
    t.cancel() # stop the timer's action if it's still waiting
    """

    def __init__(self, interval, function, args=[], kwargs={}):
        Thread.__init__(self)
        self.interval = interval
        self.function = function
        self.args = args
        self.kwargs = kwargs
        self.finished = Event()
        self.resetted = True

    def cancel(self):
        """Stop the timer if it hasn't finished yet"""
        self.finished.set()

    def run(self):
        print "Time: %s - timer running..." % time.asctime()

        while self.resetted:
            print "Time: %s - timer waiting for timeout in %.2f..." % (time.asctime(), self.interval)
            self.resetted = False
            self.finished.wait(self.interval)

        if not self.finished.isSet():
            self.function(*self.args, **self.kwargs)
        self.finished.set()
        print "Time: %s - timer finished!" % time.asctime()

    def reset(self, interval=None):
        """ Reset the timer """

        if interval:
            print "Time: %s - timer resetting to %.2f..." % (time.asctime(), interval)
            self.interval = interval
        else:
            print "Time: %s - timer resetting..." % time.asctime()

        self.resetted = True
        self.finished.set()
        self.finished.clear()

我使用以下方式运行计时器:

tim = TimerReset(10, AddBlank)
tim.start()

AddBlank函数做了一些事情,但我希望再次调用计时器,但只有在它结束后才能调用。非常感谢这方面的帮助,我知道复制代码而不理解它是不好的做法,但我真的只是想要一个简单的可重置计时器来重复调用一个函数,除非重置,这几乎就是这样。

1 个答案:

答案 0 :(得分:1)

run功能更改为:

def run(self):
    while not self.finished.isSet():
        print "Time: %s - timer running..." % time.asctime()

        self.resetted = True
        while self.resetted:
            print "Time: %s - timer waiting for timeout in %.2f..." % (time.asctime(), self.interval)
            self.resetted = False
            self.finished.wait(self.interval)

        if not self.finished.isSet():
            self.function(*self.args, **self.kwargs)
    print "Time: %s - timer finished!" % time.asctime()

这将导致它无限期地运行,直到设置finished为止。