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

时间:2016-03-09 06:20:47

标签: python-3.x python-asyncio

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

1 个答案:

答案 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