Resettable Timer object implementation python

▼魔方 西西 提交于 2021-01-29 18:33:23

问题


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

回答1:


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

Output:

Time's Up! Took 8.011203289031982 seconds




回答2:


Here is a simple example. You should consider adding locks.

import threading
import time

def hi( ):
    print('hi')
    mine.start()



class ReusableTime():
    def __init__(self, t, func):
        self._t = t
        self._func = func

    def start(self):
        self._thread = threading.Timer(self._t, self.handler)
        self._thread.start()

    def handler(self):
        self._func()


mine = ReusableTime(2, hi)
mine.start()
time.sleep(100)


来源:https://stackoverflow.com/questions/56167390/resettable-timer-object-implementation-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!