在Python中,time.sleep() 函數默認不支持設置超時。但是,你可以使用 threading.Timer 類來實現帶有超時的 sleep 功能。以下是一個示例:
import threading
def sleep_with_timeout(seconds, function):
timer = threading.Timer(seconds, function)
timer.start()
timer.join()
# 使用示例
def my_function():
print("Hello, World!")
sleep_with_timeout(5, my_function) # 設置超時時間為5秒
在這個示例中,我們定義了一個名為 sleep_with_timeout 的函數,它接受兩個參數:seconds 和 function。seconds 參數表示 sleep 的持續時間,function 參數表示要在 sleep 結束后執行的函數。
我們使用 threading.Timer 類創建一個定時器,設置其執行時間為 seconds 秒,并將要執行的函數作為參數傳遞給它。然后,我們調用 timer.start() 開始定時器,并使用 timer.join() 等待定時器完成。
這樣,你就可以實現帶有超時的 sleep 功能了。請注意,這個示例僅適用于多線程環境。如果你需要在單線程環境中實現類似的功能,可以考慮使用其他方法,例如使用信號量(Semaphore)或者協程(Coroutine)。