【发布时间】:2022-11-28 23:30:35
【问题描述】:
我正在尝试编写一个在装饰函数上调用 asyncio.wait_for 的装饰器——目标是对装饰函数设置一个时间限制。我希望装饰函数在 time_limit 之后停止运行,但事实并非如此。装饰器被调用正常,但代码只是休眠 30 秒而不是被中断。任何想法我做错了什么?
def await_time_limit(time_limit):
def Inner(func):
async def wrapper(*args, **kwargs):
return await asyncio.wait_for(func(*args, **kwargs), time_limit)
return wrapper
return Inner
@await_time_limit(5)
async def whatever
time.sleep(30) # this runs to the full 30 seconds and not stopped after 5
end
【问题讨论】:
-
asyncio.wait_for只能取消异步代码。time.sleep(30)会阻塞当前协程和整个事件循环持续 30 秒。
标签: python python-asyncio python-decorators