我想每5分钟运行一次函数,它必须以“整数”为间隔,例如:
12:05:00, 12:10:00, 12:15:00...
不能这样:
12:06:00, 12:11:00, 12:16:00...
或者这样:
12:05:14, 12:10:14, 12:15:14...
在python中最准确的方法是什么?
答案 0 :(得分:1)
您可以使用threading.Timer
。您必须做一些数学运算才能计算下一个运行时间。 datetime
有一个方便的replace
方法。
from datetime import datetime, timedelta
from threading import Timer
def get_sleep_time():
now = datetime.now()
next_run = now.replace(minute=int(now.minute / 5) * 5, second=0, microsecond=0) + timedelta(minutes=5)
return (next_run - now).total_seconds()
def dowork():
now = datetime.now()
print('Doing some work at', now)
schedule_next_run()
def schedule_next_run():
sleep_time = get_sleep_time()
print(f'sleeping for {sleep_time} seconds')
t = Timer(sleep_time, dowork)
t.daemon = True
t.start()
print('Starting work schedule')
schedule_next_run()
input('Doing work every 5 minutes. Press enter to exit')
在我的系统上,该函数会在目标时间的半毫秒内触发
请注意,时间计算会四舍五入,然后添加一个timedelta
来仔细地环绕每个小时的结束时间。您需要考虑一下夏令时变化的情况。
建议:将所有逻辑移到一个类上以进行清理。
答案 1 :(得分:1)
import datetime, time
def some_function():
ran_once = True
while True:
current_time = datetime.datetime.now()
if current_time.minute % 5 == 0 and current_time.second % 60 == 0 and not ran_once:
print(current_time) # DO YOUR WORK HERE
ran_once = True
elif current_time.minute % 5 == 0 or current_time.second % 60 != 0:
if current_time.second % 60 == 0:
print("Time to wait:", 5 - (current_time.minute % 5), "minutes and 0 seconds")
else:
print("Time to wait:", 4 - (current_time.minute % 5), "minutes and ", end="")
print(60 - (current_time.second % 60), "seconds")
time.sleep( (4 -(current_time.minute % 5))*60 + 60 -(current_time.second % 60))
ran_once = False
以上代码每5分钟运行一次。最初,主线程休眠达到理想时间戳所需的秒数。例如,如果程序在7:28:30启动,则它将休眠90秒,然后在7:30:00启动。从那时起,它将等待5分钟,然后再次运行所需的功能。
此外,我认为精确启动的性能实际上取决于系统处理线程的方式。
答案 2 :(得分:0)