我有以下代码:
@asyncio.coroutine
def do_something_periodically():
while True:
asyncio.async(my_expensive_operation())
yield from asyncio.sleep(my_interval)
if shutdown_flag_is_set:
print("Shutting down")
break
我运行此功能,直到完成。设置关闭状态时会发生问题-该功能完成并且永远不会运行任何挂起的任务。
这是错误:
task: <Task pending coro=<report() running at script.py:33> wait_for=<Future pending cb=[Task._wakeup()]>>
如何正确安排关机时间?
为了提供一些背景信息,我正在编写一个系统监视器,该监视器每5秒从/ proc / stat中读取一次,计算该时间段内的CPU使用率,然后将结果发送到服务器。我想继续计划这些监视作业,直到收到sigterm为止,当我停止计划时,等待所有当前作业完成并正常退出。
您可以检索未完成的任务并再次运行循环,直到完成为止,然后关闭循环或退出程序。
pending = asyncio.all_tasks()
loop.run_until_complete(asyncio.gather(*pending))
pending
是待处理任务的列表。asyncio.gather()
允许一次等待几个任务。如果要确保在协程内部完成所有任务(也许您有一个“主”协程),则可以这样做,例如:
async def do_something_periodically():
while True:
asyncio.create_task(my_expensive_operation())
await asyncio.sleep(my_interval)
if shutdown_flag_is_set:
print("Shutting down")
break
await asyncio.gather(*asyncio.all_tasks())
同样,在这种情况下,由于所有任务都是在同一协程中创建的,因此您已经可以访问这些任务:
async def do_something_periodically():
tasks = []
while True:
tasks.append(asyncio.create_task(my_expensive_operation()))
await asyncio.sleep(my_interval)
if shutdown_flag_is_set:
print("Shutting down")
break
await asyncio.gather(*tasks)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句