Последняя активность 10 months ago

這段程式碼使用 Python 的 threading 模組來實現非同步延遲執行。當 async_sleep(seconds) 被呼叫時,它會建立一個新的執行緒來執行 sleep() 函式,而不會阻塞主執行緒。這允許主程式繼續執行其他任務,同時在指定時間後執行 delayed_execution()。這對於需要非同步延遲執行的應用場景,如計時器或背景任務,特別有用。

async_delayed_execution.py Исходник
1import threading
2import time
3
4def delayed_execution():
5 # 在這裡執行延遲後的任務
6 print("Delayed execution")
7
8def async_sleep(seconds):
9 def sleep():
10 time.sleep(seconds)
11 delayed_execution()
12
13 thread = threading.Thread(target=sleep)
14 thread.start()
15
16# 呼叫非同步的 sleep 函數
17async_sleep(1)
18
19# 繼續執行其他任務
20print("Continuing execution")
21