与系统时钟同步的每5分钟在python中运行一个函数的最佳方法是什么? [英] What is the best way to run a function every 5 minutes in python synced with system clock?
问题描述
我想每5分钟运行一次函数,并使其与时钟同步.如果我使用time.sleep(60 * 5),则时间开始漂移,因为我的函数增加了一点处理时间.这是使我的函数与时钟同步运行的好方法,还是python中有更好的方法?
I want to run a function every 5 minutes and have it synced with the clock. If I use time.sleep(60*5), the time starts to drift because my function adds a tiny bit of processing time. Is this a good way of running my function synced with the clock or is there a better way in python?
def run(condition):
def task():
#run data here
pass
runOnce = True
while condition:
if dt.datetime.now().minute % 5 == 0 and dt.datetime.now().second == 0 and runOnce:
runOnce = False
task()
elif dt.datetime.now().second != 0 and not runOnce:
runOnce = True
else:
time.sleep(0.5)
run(True)
推荐答案
You can try APScheduler. It uses python's datetime
module to control the execution thus should be largely independent of your code's peculiarities.
from apscheduler.scheduler import BlockingScheduler
@sched.scheduled_job('interval', id='my_job_id', minutes=5)
def job_function():
print("Hello World")
Python还有一个内置的调度程序,python的sched
模块,有点简单的api,应该以相同的方式执行,并且可以避免维护额外依赖项带来的麻烦.
Python also has an inbuilt scheduler, python's sched
module with a bit simpler api that should perform in the same way and save you some hassle from maintaining an extra dependency.
这篇关于与系统时钟同步的每5分钟在python中运行一个函数的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!