受上述帖子的启发。 在Python中可取消和重置计时器。它使用线程。
特点:开始,停止,重新启动,回调函数。
输入:超时,sleep_chunk值和callback_function。
可以在任何其他程序中使用或继承此类。也可以将参数传递给回调函数。
计时器也应该在中间响应。不仅在完成睡眠时间之后。因此,不要使用一次完整的睡眠,而要使用小块睡眠,并不断检查事件对象是否在循环中。
import threading
import time
class TimerThread(threading.Thread):
def __init__(self, timeout=3, sleep_chunk=0.25, callback=None, *args):
threading.Thread.__init__(self)
self.timeout = timeout
self.sleep_chunk = sleep_chunk
if callback == None:
self.callback = None
else:
self.callback = callback
self.callback_args = args
self.terminate_event = threading.Event()
self.start_event = threading.Event()
self.reset_event = threading.Event()
self.count = self.timeout/self.sleep_chunk
def run(self):
while not self.terminate_event.is_set():
while self.count > 0 and self.start_event.is_set():
# print self.count
# time.sleep(self.sleep_chunk)
# if self.reset_event.is_set():
if self.reset_event.wait(self.sleep_chunk): # wait for a small chunk of timeout
self.reset_event.clear()
self.count = self.timeout/self.sleep_chunk # reset
self.count -= 1
if self.count <= 0:
self.start_event.clear()
#print 'timeout. calling function...'
self.callback(*self.callback_args)
self.count = self.timeout/self.sleep_chunk #reset
def start_timer(self):
self.start_event.set()
def stop_timer(self):
self.start_event.clear()
self.count = self.timeout/self.sleep_chunk # reset
def restart_timer(self):
# reset only if timer is running. otherwise start timer afresh
if self.start_event.is_set():
self.reset_event.set()
else:
self.start_event.set()
def terminate(self):
self.terminate_event.set()
#=================================================================
def my_callback_function():
print 'timeout, do this...'
timeout = 6 # sec
sleep_chunk = .25 # sec
tmr = TimerThread(timeout, sleep_chunk, my_callback_function)
tmr.start()
quit = '0'
while True:
quit = raw_input("Proceed or quit: ")
if quit == 'q':
tmr.terminate()
tmr.join()
break
tmr.start_timer()
if raw_input("Stop ? : ") == 's':
tmr.stop_timer()
if raw_input("Restart ? : ") == 'r':
tmr.restart_timer()
这是最好的。如果你的程序没有立即终止,那么这将是*好的*,只有一个“你好”并且没有任何延迟! :)你必须根据某些条件将't.cancel()'合并到'sayHello()'函数中。 'if counter == 10:t.cancel()'。那会有意义的。 – Apostolos 2018-03-01 22:45:21
对不起。即使那样也不会很好。如果在调用'sayHello(0)'后添加任何代码,它将在定时器测试结束前执行! (自己动手,在代码末尾添加例如'print'Done'')。 – Apostolos 2018-03-01 23:12:36