[英]How to execute a function every n seconds in python using aysncio
[英]python execute function every n seconds wait for completion
我想每 60 秒定期執行一次 FUNCTION,但如果上次運行尚未完成,我不想再次執行 FUNCTION。 如果上一次運行在例如 120 秒內完成,那么我想立即執行一個新的 FUNCTION 調用。 如果上一次運行在例如 10 秒內完成,那么我想在執行新的 FUNCTION 調用之前等待 50 秒。
請在下面查看我的實現。
我可以使用例如 subprocess.run 或一些 timeloop 庫來實現它,以便實現更清晰嗎?
import time
def hello(x):
# some logic here
# execution could take any time between e.g. <10s, 120s>
def main(ii):
while True:
start = int(time.time())
try:
val = next(ii)
except StopIteration as ex:
return None
else:
hello(val)
run_time_diff = int(time.time()) - start
if run_time_diff < 60:
time.sleep(60 - run_time_diff)
ii = iter(list[[...],[...],...[...]])
main(ii=ii)
也許 apsheduler 可以幫助你。 但是,如果您的工作運行時間超過等待時間,則可以跳過它。 在這種情況下,您可以增加工人數量。
import datetime
import time
from apscheduler.schedulers.background import BackgroundScheduler
scheduler = BackgroundScheduler()
def some_job():
time.sleep(5)
print(f"{datetime.datetime.utcnow()}: Every 10 seconds")
job = scheduler.add_job(some_job, 'interval', seconds=10, max_instances=1)
scheduler.start()
try:
while True:
time.sleep(1)
finally:
scheduler.shutdown()
你好,你把return 0
。 在 main 函數中,在 while 中,在 else 中,你像我一樣放置了一個循環
x = hello(val)
if x = 0:
# Your custom code after function will be excute
main()
else:
# Re-excute the function if it not work
hello(val)
但我不確定我的x
在定義時,它會執行hello()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.