Última atividade 10 months ago

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

timmy revisou este gist 10 months ago. Ir para a revisão

1 file changed, 20 insertions

async_delayed_execution.py(arquivo criado)

@@ -0,0 +1,20 @@
1 + import threading
2 + import time
3 +
4 + def delayed_execution():
5 + # 在這裡執行延遲後的任務
6 + print("Delayed execution")
7 +
8 + def 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 函數
17 + async_sleep(1)
18 +
19 + # 繼續執行其他任務
20 + print("Continuing execution")
Próximo Anterior