async_delayed_execution_with_threading.py
· 572 B · Python
Неформатований
import asyncio
import threading
import time
async def delayed_execution():
# 在這裡執行延遲後的任務
print("Delayed execution")
def blocking_sleep(seconds):
time.sleep(seconds)
async def async_sleep(seconds):
loop = asyncio.get_running_loop()
await loop.run_in_executor(None, blocking_sleep, seconds)
await delayed_execution()
async def main():
# 呼叫非同步的 sleep 函數
await async_sleep(1)
# 繼續執行其他任務
print("Continuing execution")
# 建立事件迴圈並執行主程式
asyncio.run(main())
| 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()) |
| 26 |