[英]How to handle Timeout Exception by the asyncio task itself just before asyncio raise TimeoutError
由於一個用例,我的一個長時間運行的函數執行了多條指令。 但我必須為其執行提供最長時間。 如果function不能在分配的時間內完成執行,它應該清理進度並返回。
讓我們看一下下面的示例代碼:
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())
function eternity
是長期運行的 function。要注意的是,如果出現某些異常或達到最大分配時間,function 需要清理它造成的混亂。
PS eternity
是一個獨立的 function 只有它能理解要清理什么。
我正在尋找一種方法在超時之前在我的任務中引發異常,或者向任務發送一些中斷或終止信號並處理它。
基本上,我想在 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())
這是 output:
I have to clean up lot of thing in case of Exception or not able to finish by the allocated time
timeout!
有關詳細信息,請查看此處。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.