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

发布于 2021-01-29 15:08:33

我从迁移tornadoasyncio了,我找不到asyncio等效tornadoPeriodicCallback。(APeriodicCallback有两个参数:要运行的函数和两次调用之间的毫秒数。)

  • 有这样的等同物asyncio吗?
  • 如果没有,那么在没有冒RecursionError一会儿风险的情况下实现此目标的最干净方法是什么?
关注者
0
被浏览
63
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    对于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
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看