[英]Run a function at the start of every round 5 minute interval
I want to run a function every 5 minutes, it must be at a "round" intervals, for example:我想每 5 分钟运行一次 function,它必须以“轮”间隔运行,例如:
12:05:00, 12:10:00, 12:15:00...
It cannot be like this:不能是这样的:
12:06:00, 12:11:00, 12:16:00...
Or like this:或者像这样:
12:05:14, 12:10:14, 12:15:14...
What is the most accurate way to do this in python?在 python 中执行此操作的最准确方法是什么?
You could use a threading.Timer
.您可以使用
threading.Timer
。 You have to do some math to calculate the next run time.您必须做一些数学运算来计算下一次运行时间。
datetime
has a handy replace
method for that. 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')
On my system, the function fires within a half millisecond of the target time在我的系统上,function 在目标时间的半毫秒内触发
Note that the time calculation rounds down and then adds a timedelta
to carefully wrap around the end of each hour.请注意,时间计算会向下取整,然后添加一个
timedelta
以仔细环绕每个小时的结束。 You would want to ponder how this will behave around daylight savings changes.您可能想考虑这将如何围绕夏令时变化进行。
Suggestion : move all this logic to a class to clean it up.建议:将所有这些逻辑移至 class 进行清理。
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
The above code runs at intervals of 5 minutes.上面的代码每隔 5 分钟运行一次。 Initially, the main thread sleeps for the number of seconds required to reach the perfect timestamp.
最初,主线程休眠达到完美时间戳所需的秒数。 For example, if the program is started at 7:28:30 then it is going to sleep for 90 seconds and then start at 7:30:00.
例如,如果程序在 7:28:30 开始,那么它将休眠 90 秒,然后在 7:30:00 开始。 From then on it will wait for 5 minutes before it runs the required functionality again.
从那时起,它将等待 5 分钟,然后再次运行所需的功能。
Also, I think the performance of firing up at the exact second really varies on how your system handles the threads.此外,我认为在确切的一秒启动的性能确实因系统处理线程的方式而异。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.