asyncio.sleep能停止吗?

1 投票
2 回答
67 浏览
提问于 2025-04-12 08:59

你能让 asyncio.sleep() 停止休眠吗?我想在一个协程中运行一些代码,要么是在等待20秒后,要么是在某个布尔值为真的时候,有没有办法做到这一点?我现在只想到这样实现:

while t < 20 and not value:
    asyncio.sleep(1)
    t +=1
...

有没有更符合Python风格的方法来做到这一点?

2 个回答

1

如果我理解得没错,你可以使用 asyncio.Future()asyncio.wait_for() 这两个东西:

import asyncio


async def task_fn(fut: asyncio.Future):
    await asyncio.sleep(2)  # <-- after 2 seconds set the Future's result to True
    fut.set_result(True)


async def main():
    task = asyncio.Task(task_fn(fut := asyncio.Future()))

    try:
        await asyncio.wait_for(fut, 3)    # <-- wait 3 seconds for the future result
        print("OK, task finished within 3 seconds")
    except TimeoutError:
        print("Error, task didn't finish within 3 seconds")


asyncio.run(main())

这段代码会输出:

OK, task finished within 3 seconds

如果你把 task_fn 改成:

async def task_fn(fut: asyncio.Future):
    await asyncio.sleep(5)  # <--- notice the 5 seconds
    fut.set_result(True)

那么结果会变成:

Error, task didn't finish within 3 seconds

撰写回答