在 python 3.4 中,每次循环完成后永远重复事件循环

Forever repeat of an eventloop after each loop completion, in python 3.4

我正在使用 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()

没有重复任务的机制 - 包装它 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