如何使用 asyncio 定期执行函数? [英] How can I periodically execute a function with asyncio?

查看:82
本文介绍了如何使用 asyncio 定期执行函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm migrating from tornado to asyncio, and I can't find the asyncio equivalent of tornado's PeriodicCallback. (A PeriodicCallback takes two arguments: the function to run and the number of milliseconds between calls.)

  • asyncio 中是否有这样的等价物?
  • 如果不是,那么在不冒出现 RecursionError 的风险的情况下,最简洁的实现方法是什么?
  • Is there such an equivalent in asyncio?
  • If not, what would be the cleanest way to implement this without running the risk of getting a RecursionError after a while?

推荐答案

对于低于 3.5 的 Python 版本:

For Python versions below 3.5:

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 及更高版本:

For Python 3.5 and above:

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

这篇关于如何使用 asyncio 定期执行函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆