it-swarm.dev

如何定期使用asyncio执行功能?

我正在从tornado迁移到asyncio,但找不到与asynciotornado等效的PeriodicCallback。 (PeriodicCallback带有两个参数:要运行的函数和两次调用之间的毫秒数。)

  • asyncio有这样的等效项吗?
  • 如果不是,那么最干净的方法是什么,而又不冒一段时间后获得RecursionError的风险?
45
2Cubed

对于3.5以下的Python版本:

import asyncio

@asyncio.coroutine
def periodic():
    while True:
        print('periodic')
        yield from asyncio.sleep(1)

def stop():
    task.cancel()

loop = asyncio.get_event_loop()
loop.call_later(5, stop)
task = loop.create_task(periodic())

try:
    loop.run_until_complete(task)
except asyncio.CancelledError:
    pass

对于Python 3.5及更高版本:

import asyncio

async def periodic():
    while True:
        print('periodic')
        await asyncio.sleep(1)

def stop():
    task.cancel()

loop = asyncio.get_event_loop()
loop.call_later(5, stop)
task = loop.create_task(periodic())

try:
    loop.run_until_complete(task)
except asyncio.CancelledError:
    pass
35
A. Jesse Jiryu Davis

当您认为应该在asyncio程序的“后台”发生某些事情时,asyncio.Task可能是执行此操作的好方法。您可以阅读 本文 以了解如何处理任务。

这是定期执行某些功能的类的可能实现:

import asyncio
from contextlib import suppress


class Periodic:
    def __init__(self, func, time):
        self.func = func
        self.time = time
        self.is_started = False
        self._task = None

    async def start(self):
        if not self.is_started:
            self.is_started = True
            # Start task to call func periodically:
            self._task = asyncio.ensure_future(self._run())

    async def stop(self):
        if self.is_started:
            self.is_started = False
            # Stop task and await it stopped:
            self._task.cancel()
            with suppress(asyncio.CancelledError):
                await self._task

    async def _run(self):
        while True:
            await asyncio.sleep(self.time)
            self.func()

让我们测试一下:

async def main():
    p = Periodic(lambda: print('test'), 1)
    try:
        print('Start')
        await p.start()
        await asyncio.sleep(3.1)

        print('Stop')
        await p.stop()
        await asyncio.sleep(3.1)

        print('Start')
        await p.start()
        await asyncio.sleep(3.1)
    finally:
        await p.stop()  # we should stop task finally


if __== '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

输出:

Start
test
test
test

Stop

Start
test
test
test

[Finished in 9.5s]

如您在start上看到的,我们只是启动任务,该任务调用一些函数并在无穷循环中休眠一些时间。在stop上,我们只是取消了该任务。注意,该程序应在程序完成时停止。

更重要的一件事是您的回调不应该花费太多时间来执行(否则它将冻结事件循环)。如果您打算调用一些长期运行的func,则可能需要 在执行程序中运行它

19
Mikhail Gerasimov

没有对定期呼叫的内置支持。

只需创建您自己的调度程序循环即可休眠并执行任何调度的任务:

import math, time

async def scheduler():
    while True:
        # sleep until the next whole second
        now = time.time()
        await asyncio.sleep(math.ceil(now) - now)

        # execute any scheduled tasks
        await for task in scheduled_tasks(time.time()):
            await task()

scheduled_tasks()迭代器应生成准备在给定时间运行的任务。请注意,从理论上讲,制定时间表并启动所有任务可能要花费超过1秒的时间;这里的想法是,调度程序产生自上次检查以来应该已经启动的所有任务。

15
Martijn Pieters

带有python 3.7装饰的替代版本

import asyncio
import time


def periodic(period):
    def scheduler(fcn):

        async def wrapper(*args, **kwargs):

            while True:
                asyncio.create_task(fcn(*args, **kwargs))
                await asyncio.sleep(period)

        return wrapper

    return scheduler


@periodic(2)
async def do_something(*args, **kwargs):
    await asyncio.sleep(5)  # Do some heavy calculation
    print(time.time())


if __== '__main__':
    asyncio.run(do_something('Maluzinha do papai!', secret=42))

一种变体可能会有所帮助:如果您希望您的重复调用每隔n秒而不是上一次执行的结束与下一次执行的开始之间的n秒发生一次,并且您不希望调用在时间上重叠,请执行以下操作:更简单:

async def repeat(interval, func, *args, **kwargs):
    """Run func every interval seconds.

    If func has not finished before *interval*, will run again
    immediately when the previous iteration finished.

    *args and **kwargs are passed as the arguments to func.
    """
    while True:
        await asyncio.gather(
            func(*args, **kwargs),
            asyncio.sleep(interval),
        )

以及使用它在后台运行几个任务的示例:

async def f():
    await asyncio.sleep(1)
    print('Hello')


async def g():
    await asyncio.sleep(0.5)
    print('Goodbye')


async def main():
    t1 = asyncio.ensure_future(repeat(3, f))
    t2 = asyncio.ensure_future(repeat(2, g))
    await t1
    await t2

loop = asyncio.get_event_loop()
loop.run_until_complete(main())
1
Fred Ross

基于@A。 Jesse Jiryu Davis的回复(带有@TorkelBjørnson-Langen和@ReWrite注释),这是一种避免漂移的改进。

import time
import asyncio

@asyncio.coroutine
def periodic(period):
    def g_tick():
        t = time.time()
        count = 0
        while True:
            count += 1
            yield max(t + count * period - time.time(), 0)
    g = g_tick()

    while True:
        print('periodic', time.time())
        yield from asyncio.sleep(next(g))

loop = asyncio.get_event_loop()
task = loop.create_task(periodic(1))
loop.call_later(5, task.cancel)

try:
    loop.run_until_complete(task)
except asyncio.CancelledError:
    pass
1
Wojciech Migda