在Linux中,你不能直接中斷一個毫秒級的sleep
import time
import threading
def sleep_with_timeout(seconds, timeout):
def sleep_thread():
nonlocal seconds
start_time = time.time()
while True:
remaining_time = seconds - (time.time() - start_time)
if remaining_time <= 0:
break
time.sleep(0.001)
thread = threading.Thread(target=sleep_thread)
thread.start()
if timeout > 0:
time.sleep(timeout)
if thread.is_alive():
print("Interrupting sleep...")
thread.join()
else:
thread.join()
# 使用示例
sleep_with_timeout(5, 2) # 讓線程睡眠5秒,但最多等待2秒
在這個示例中,我們創建了一個名為sleep_with_timeout的函數,它接受兩個參數:seconds表示要睡眠的總時間,timeout表示允許的最大等待時間。我們使用一個單獨的線程來執行sleep操作,并在到達最大等待時間后嘗試中斷它。請注意,這種方法并不能保證在毫秒級別精確地中斷sleep,但它可以確保在指定的超時時間內停止睡眠。