可重置定时器对象实现python

编程入门 行业动态 更新时间:2024-10-25 18:27:49
本文介绍了可重置定时器对象实现python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我需要一个可以重置的 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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-30 11:09:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1392832.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:定时器   对象   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!