可重置定时器对象实现python [英] Resettable Timer object implementation python

查看:25
本文介绍了可重置定时器对象实现python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个可以重置的 Python 计时器 (timer.reset()).我已经有一个定期计时器.有没有这种定时器的库?

I need a timer in Python which i can reset (timer.reset()). I already have a periodic timer. Is there a library with such a timer?

class MyTimer(threading.Timer):
    def __init__(self, t):
        threading.Thread.__init__(self)
        self.__event = threading.Event()
        self.__stop_event = threading.Event()
        self.__intervall = t

    def run(self):
        while not self.__stop_event.wait(self.__intervall):
            self.__event.set()

    def clear(self):
        self.__event.clear()

    def is_present(self):
        return self.__event.is_set()

    def cancel(self):
        self.__stop_event.set()

推荐答案

下面是一个示例,它实现了一个 reset 方法,以将计时器延长"到原始间隔.它使用内部 Timer 对象,而不是子类化 threading.Timer.

Here's an example that implements a reset method to "extend" the timer by the original interval. It uses an internal Timer object rather than subclassing threading.Timer.

from threading import Timer
import time


class ResettableTimer(object):
    def __init__(self, interval, function):
        self.interval = interval
        self.function = function
        self.timer = Timer(self.interval, self.function)

    def run(self):
        self.timer.start()

    def reset(self):
        self.timer.cancel()
        self.timer = Timer(self.interval, self.function)
        self.timer.start()


if __name__ == '__main__':
    t = time.time()
    tim = ResettableTimer(5, lambda: print("Time's Up! Took ", time.time() - t, "seconds"))
    time.sleep(3)
    tim.reset()

输出:

时间到了!花了 8.011203289031982 秒

这篇关于可重置定时器对象实现python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆