Lấy cảm hứng từ bài đăng ở trên. Có thể hủy và đặt lại bộ hẹn giờ bằng Python. Nó sử dụng thread.
Các tính năng: Khởi động, Dừng, Khởi động lại, chức năng gọi lại.
Nhập: Thời gian chờ, giá trị sleep_chunk và callback_function.
Có thể sử dụng hoặc kế thừa lớp này trong bất kỳ chương trình nào khác. Cũng có thể chuyển đối số cho hàm gọi lại.
Bộ hẹn giờ cũng sẽ phản hồi ở giữa. Không chỉ sau khi hoàn thành thời gian ngủ đầy đủ. Vì vậy, thay vì sử dụng một giấc ngủ đầy đủ, sử dụng các đoạn nhỏ của giấc ngủ và tiếp tục kiểm tra đối tượng sự kiện trong vòng lặp.
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()
Đó là _almost_ tốt. Nó sẽ được * tốt * nếu chương trình của bạn đã không chấm dứt ngay lập tức, với một "Hello" và không có sự chậm trễ nào cả! :) Bạn phải kết hợp 't.cancel()' vào hàm 'sayHello()' dựa trên một số điều kiện, ví dụ: 'if counter == 10: t.cancel()'. Sau đó nó sẽ có một ý nghĩa. – Apostolos
Xin lỗi. Nó sẽ không được tốt ngay cả sau đó. Nếu bạn thêm bất kỳ mã nào sau khi gọi 'sayHello (0)', nó sẽ được thực hiện trước khi kiểm tra bộ đếm thời gian kết thúc! (Hãy tự mình thử nghiệm, bằng cách thêm ví dụ: "in" Xong "' ở cuối mã của bạn.) – Apostolos