[英]Run a function every n seconds in python with asyncio
I have an application which already runs infinitely with asyncio event loop run forever and also I need to run a specific function every 10 seconds.我有一个应用程序已经无限运行,asyncio 事件循环永远运行,而且我需要每 10 秒运行一次特定的函数。
def do_something():
pass
a = asyncio.get_event_loop()
a.run_forever()
I would like to call the function do_something every 10 seconds.我想每 10 秒调用一次函数 do_something。 How to achieve this without replacing asynctio event loop with while loop ?如何在不使用 while 循环替换 asynctio 事件循环的情况下实现这一点?
Edited: I can achieve this with the below code编辑:我可以用下面的代码实现这一点
def do_something():
pass
while True:
time.sleep(10)
do_something()
But I dont want to use while loop to run infinitely in my application instead I would like to go with asyncio run_forever().但是我不想使用 while 循环在我的应用程序中无限运行,而是想使用 asyncio run_forever()。 So how to call the same function every 10 seconds with asyncio ?那么如何使用 asyncio 每 10 秒调用一次相同的函数呢? is there any scheduler like which will not block my ongoing work ?是否有任何调度程序不会阻止我正在进行的工作?
You can achieve it with你可以实现它
def do_something():
await asyncio.wait(10)
...rest of code...
asyncio
does not ship with a builtin scheduler, but it is easy enough to build your own. asyncio
不附带内置调度程序,但构建您自己的调度程序很容易。 Simply combine a while
loop with asyncio.sleep
to run code every few seconds.只需将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()
Note that the design has to be slightly different if func
is itself a coroutine or a long-running subroutine.请注意,如果func
本身是协同程序或长时间运行的子程序,则设计必须略有不同。 In the former case use await func(...)
and in the latter case use asyncio
's thread capabilities .在前一种情况下使用await func(...)
,在后一种情况下使用asyncio
的线程功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.