【问题标题】:Python Asyncio wait_for decoratorPython Asyncio wait_for 装饰器
【发布时间】: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

【问题讨论】:

标签: python python-asyncio python-decorators


【解决方案1】:

正如我们在此处的示例中所见,问题出在使用time.sleep 而不是asyncio.sleep,因为time.sleep 会阻塞线程。您需要注意不要有任何阻塞代码

import asyncio
import time


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 asleep():
    await asyncio.sleep(30) # this runs for only 5 seconds


@await_time_limit(5)
async def ssleep():
    time.sleep(30) # this runs to the full 30 seconds and not stopped after 5


t1 = time.time()
await asleep()
t2 = time.time()
print(t2-t1) # 5.018370866775513


t1 = time.time()
await ssleep()
t2 = time.time()
print(t2-t1) # 30.00193428993225

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-07
    • 2014-01-23
    • 1970-01-01
    • 2021-05-20
    • 2020-02-10
    • 2011-11-04
    相关资源
    最近更新 更多