我在Python中需要一个可以重置的计时器(timer.reset())。 我已经有一个定期计时器。 有没有带计时器的图书馆?
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()
答案 0 :(得分:1)
下面是一个示例,该示例实现一种reset
方法以将计时器“扩展”原始间隔。它使用内部Timer
对象,而不是子类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()
输出:
Time's Up! Took 8.011203289031982 seconds
答案 1 :(得分:0)
这是一个简单的例子。您应该考虑添加锁。
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)