简体   繁体   English

如何使用 aysncio 在 python 中每隔 n 秒执行一次 function

[英]How to execute a function every n seconds in python using aysncio

Basically I got a function, I want it to repeat infinitely with the interval of 30 seconds.基本上我得到了一个 function,我希望它以 30 秒的间隔无限重复。 is it possible to do this with async def function?是否可以使用 async def function 来做到这一点?

async def test():
  await print("Hello")

how to repeat it after every 30 seconds?如何在每 30 秒后重复一次?

Use asyncio.sleep in a while loop to do it:在 while 循环中使用asyncio.sleep来执行此操作:

import asyncio


async def test():
    while True:
        print("Hello")
        await asyncio.sleep(30)

if __name__ == '__main__':
    asyncio.run(test())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM