import asyncio
from asyncio.exceptions import TimeoutError
async def play_music(music: str):
print(f"{music} is started")
await asyncio.sleep(3)
print(f"{music} is finished")
return music
async def call_api():
print("call_api")
raise Exception("it is a Exception")
# 将协程任务结束
async def my_cancel():
task = asyncio.create_task(play_music("A music"))
await asyncio.sleep(4)
if not task.done():
task.cancel()
# 协程任务超时退出 如果超时会抛出异常然后退出 TimeoutError 需要异常处理
async def my_cancel_timeout():
task = asyncio.create_task(play_music("B music"))
try:
await asyncio.wait_for(task,timeout=2)
except TimeoutError:
print("timeout error!!")
# 协程任务超时抛出异常 但不退出任务继续执行 asyncio.shield函数保护task任务
async def my_timeout():
task = asyncio.create_task(play_music("B music"))
try:
await asyncio.wait_for(asyncio.shield(task), timeout=2)
except TimeoutError:
print("timeout error!!")
await task
# asyncio.gather 直接并行多个任务并等待结束,返回结果
async def my_gather():
task = await asyncio.gather(play_music("A"),play_music("B"))
print(task)
# 直接并行多个任务,并且并且捕捉异常,return_exceptions=True
async def my_gather_exception():
task = await asyncio.gather(play_music("A"),play_music("B"),call_api(),return_exceptions=True)
print(task)
if __name__ == "__main__":
asyncio.run(my_gather_exception())
python 协程任务结束,超时,多任务并行,异常
最新推荐文章于 2024-06-19 20:44:34 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)