timmy gist felülvizsgálása 10 months ago. Revízióhoz ugrás
1 file changed, 25 insertions
async_delayed_execution_with_threading.py(fájl létrehozva)
| @@ -0,0 +1,25 @@ | |||
| 1 | + | import asyncio | |
| 2 | + | import threading | |
| 3 | + | import time | |
| 4 | + | ||
| 5 | + | async def delayed_execution(): | |
| 6 | + | # 在這裡執行延遲後的任務 | |
| 7 | + | print("Delayed execution") | |
| 8 | + | ||
| 9 | + | def blocking_sleep(seconds): | |
| 10 | + | time.sleep(seconds) | |
| 11 | + | ||
| 12 | + | async def async_sleep(seconds): | |
| 13 | + | loop = asyncio.get_running_loop() | |
| 14 | + | await loop.run_in_executor(None, blocking_sleep, seconds) | |
| 15 | + | await delayed_execution() | |
| 16 | + | ||
| 17 | + | async def main(): | |
| 18 | + | # 呼叫非同步的 sleep 函數 | |
| 19 | + | await async_sleep(1) | |
| 20 | + | ||
| 21 | + | # 繼續執行其他任務 | |
| 22 | + | print("Continuing execution") | |
| 23 | + | ||
| 24 | + | # 建立事件迴圈並執行主程式 | |
| 25 | + | asyncio.run(main()) | |
Újabb
Régebbi