【问题标题】:Using wait_for with timeouts with list of tasks使用带有超时的 wait_for 和任务列表
【发布时间】:2019-10-04 21:19:53
【问题描述】:

所以,我有一个任务列表,我想以非阻塞方式同时安排这些任务。 基本上,gather 应该可以解决问题。 喜欢

tasks = [ asyncio.create_task(some_task()) in bleh]
results = await asyncio.gather(*tasks)

但是,我也需要超时。我想要的是任何需要>超时时间的任务都会取消,我会继续我所拥有的。

我犯规了asyncio.wait 原始人。 https://docs.python.org/3/library/asyncio-task.html#waiting-primitives

但是医生说: Run awaitable objects in the aws set concurrently and block until the condition specified by return_when.

这似乎表明它会阻止......

似乎 asyncio.wait_for 可以解决问题 https://docs.python.org/3/library/asyncio-task.html#timeouts 但是我如何发送等待列表而不是等待列表?

【问题讨论】:

    标签: python-asyncio python-3.7


    【解决方案1】:

    我想要的是任何需要>超时时间的任务都会取消,然后我会继续我所拥有的。

    这很容易通过asyncio.wait() 实现:

    # Wait for tasks to finish, but no more than a second.
    done, pending = await asyncio.wait(tasks, timeout=1)
    # Cancel the ones not done by now.
    for fut in pending:
        fut.cancel()
    # Results are available as x.result() on futures in `done`
    

    这似乎表明 [asyncio.wait] 阻塞...

    它只阻塞当前协程,与gatherwait_for相同。

    【讨论】:

    • 感谢您的回复。你知道什么时候使用asyncio.as_completed。看起来很像asyncio.wait
    • @Fraz as_completed 适用于当您对任务到达时的结果感兴趣时。 wait 将等待所有完成(默认情况下)或第一个完成(如果给定 return_when=FIRST_COMPLETED)。我通常发现wait() 在实践中更有用,特别是因为它的返回值会为您提供哪些任务已完成和哪些尚未完成的信息,答案中的代码可以很好地利用这些信息。
    猜你喜欢
    • 1970-01-01
    • 2017-02-27
    • 2021-06-28
    • 2013-10-20
    • 2020-02-19
    • 1970-01-01
    • 1970-01-01
    • 2016-07-26
    • 1970-01-01
    相关资源
    最近更新 更多