[英]Using asyncio to run a function at the start (00 seconds) of every minute
[英]Run a function every n seconds in python with asyncio
我有一个应用程序已经无限运行,asyncio 事件循环永远运行,而且我需要每 10 秒运行一次特定的函数。
def do_something():
pass
a = asyncio.get_event_loop()
a.run_forever()
我想每 10 秒调用一次函数 do_something。 如何在不使用 while 循环替换 asynctio 事件循环的情况下实现这一点?
编辑:我可以用下面的代码实现这一点
def do_something():
pass
while True:
time.sleep(10)
do_something()
但是我不想使用 while 循环在我的应用程序中无限运行,而是想使用 asyncio run_forever()。 那么如何使用 asyncio 每 10 秒调用一次相同的函数呢? 是否有任何调度程序不会阻止我正在进行的工作?
你可以实现它
def do_something():
await asyncio.wait(10)
...rest of code...
asyncio
不附带内置调度程序,但构建您自己的调度程序很容易。 只需将while
循环与asyncio.sleep
结合起来while
每隔几秒钟运行一次代码。
async def every(__seconds: float, func, *args, **kwargs):
while True:
func(*args, **kwargs)
await asyncio.sleep(__seconds)
a = asyncio.get_event_loop()
a.create_task(every(1, print, "Hello World"))
...
a.run_forever()
请注意,如果func
本身是协同程序或长时间运行的子程序,则设计必须略有不同。 在前一种情况下使用await func(...)
,在后一种情况下使用asyncio
的线程功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.