我正在使用python 3.4。 我试图让几个任务的循环异步运行,当一个循环循环完成后,再次循环从开始循环。只有在最后一轮完成后才有必要再次启动循环。我认为这段代码可能是我正在寻找的,但它只运行一次。
import asyncio
@asyncio.coroutine
def some_task(name, number):
print('task ', name, ' started')
yield from asyncio.sleep(number)
print('task ', name, ' finished')
@asyncio.coroutine
def loop_executer(loop, tasks):
if not loop.is_running():
loop.run_until_complete(asyncio.wait(tasks))
tasks = [
asyncio.ensure_future(some_task("A", 2)),
asyncio.ensure_future(some_task("B", 5)),
asyncio.ensure_future(some_task("C", 4))]
ev_loop = asyncio.get_event_loop()
ev_loop.create_task(loop_executer(ev_loop, tasks))
ev_loop.run_forever()
答案 0 :(得分:1)
没有重复任务的机制 - 将其包裹while
循环。
import asyncio
@asyncio.coroutine
def some_task(name, number):
print('task ', name, ' started')
yield from asyncio.sleep(number)
print('task ', name, ' finished')
@asyncio.coroutine
def loop_executer(loop):
# you could use even while True here
while loop.is_running():
tasks = [
some_task("A", 2),
some_task("B", 5),
some_task("C", 4)
]
yield from asyncio.wait(tasks)
ev_loop = asyncio.get_event_loop()
ev_loop.create_task(loop_executer(ev_loop))
ev_loop.run_forever()
您不必在协同程序上使用ensure_future
。