![](/img/trans.png)
[英]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.