在任务列表中使用 wait_for 超时
Using wait_for with timeouts with list of tasks
所以,我有一个任务列表,我想以非阻塞方式同时安排这些任务。
基本上,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
但是我如何发送可等待列表而不仅仅是一个可等待列表?
What I want is that any task which takes > timeout time cancels and I proceed with what I have.
这很容易实现 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`
Which seems to suggest that [asyncio.wait] blocks...
只阻塞当前协程,与gather
或wait_for
相同。
所以,我有一个任务列表,我想以非阻塞方式同时安排这些任务。
基本上,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 但是我如何发送可等待列表而不仅仅是一个可等待列表?
What I want is that any task which takes > timeout time cancels and I proceed with what I have.
这很容易实现 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`
Which seems to suggest that [asyncio.wait] blocks...
只阻塞当前协程,与gather
或wait_for
相同。