如何定期使用asyncio执行功能?
发布于 2021-01-29 15:08:33
我从迁移tornado
到asyncio
了,我找不到asyncio
等效tornado
的PeriodicCallback
。(APeriodicCallback
有两个参数:要运行的函数和两次调用之间的毫秒数。)
- 有这样的等同物
asyncio
吗? - 如果没有,那么在没有冒
RecursionError
一会儿风险的情况下实现此目标的最干净方法是什么?
关注者
0
被浏览
63
1 个回答
-
对于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