asyncio.sleep可以停止吗?

问题描述 投票:0回答:1

你能阻止

asyncio.sleep()
睡觉吗?我想在等待 20 秒后或布尔值为 true 时在协程中运行一些代码,有什么办法可以做到这一点吗?我只能想到这样实现:

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

有没有更Pythonic的方法来做到这一点?

python asynchronous async-await python-asyncio
1个回答
0
投票

IIUC,您可以使用

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 doesn't finished 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 doesn't finished within 3 seconds
© www.soinside.com 2019 - 2024. All rights reserved.