如何在asyncio引发TimeoutError之前由asyncio任务本身处理Timeout Exception.&l



由于一个用例,我的一个长时间运行的函数执行多个指令。但我必须给出执行的最长时间。如果函数不能在分配的时间内完成它的执行,它应该清理进程并返回。

让我们看一下下面的示例代码:

import asyncio
async def eternity():
# Sleep for one hour
try:
await asyncio.sleep(3600)
print('yay!, everything is done..')
except Exception as e:
print("I have to clean up lot of thing in case of Exception or not able to finish by the allocated time")

async def main():
try:
ref = await asyncio.wait_for(eternity(), timeout=5)
except asyncio.exceptions.TimeoutError:
print('timeout!')
asyncio.run(main())

函数eternity为长时间运行函数。问题是,在出现异常或达到最大分配时间的情况下,该函数需要清理它所造成的混乱。

注:eternity是一个独立的函数,只有它才知道要清洗什么。

我正在寻找一种方法来在超时之前在我的任务中引发异常,或者发送一些中断或终止信号到任务并处理它。基本上,我想在asyncio引发TimeoutError并控制之前在我的任务中执行一些代码。
另外,我正在使用Python 3.9。
希望我能解释这个问题。

您需要的是异步上下文管理器:

import asyncio
class MyClass(object):
async def eternity(self):
# Sleep for one hour
await asyncio.sleep(3600)
print('yay!, everything is done..')
async def __aenter__(self):
return self
async def __aexit__(self, exc_type, exc, tb):
print("I have to clean up lot of thing in case of Exception or not able to finish by the allocated time")

async def main():
try:
async with MyClass() as my_class:
ref = await asyncio.wait_for(my_class.eternity(), timeout=5)
except asyncio.exceptions.TimeoutError:
print('timeout!')

asyncio.run(main())

输出:

I have to clean up lot of thing in case of Exception or not able to finish by the allocated time
timeout!

更多细节请看这里。

最新更新