Skip to main content
 首页 » 编程设计

python之如何在不等待的情况下运行 Asyncio 任务

2024年11月24日9oomusou

<分区>

我需要定期调用任务,但 (a) 等待时间几乎超过了周期。

在下面的代码中,如何运行 do_something() 任务而不需要 await 获取结果?

 import asyncio 
 import time 
 from random import randint 
 
 period = 1  # Second 
 
 
 def get_epoch_ms(): 
     return int(time.time() * 1000.0) 
 
 
 async def do_something(name): 
     print("Start  :", name, get_epoch_ms()) 
     try: 
         # Do something which may takes more than 1 secs. 
         slp = randint(1, 5) 
         print("Sleep  :", name, get_epoch_ms(), slp) 
         await asyncio.sleep(slp) 
     except Exception as e: 
         print("Error  :", e) 
 
     print("Finish :", name, get_epoch_ms()) 
 
 
 async def main(): 
     i = 0 
     while True: 
         i += 1 
         # Todo : this line should be change 
         await do_something('T' + str(i)) 
         await asyncio.sleep(period) 
 
 
 asyncio.get_event_loop().run_until_complete(main())