首页 > 解决方案 > 在每轮开始时运行一个函数,间隔 5 分钟

问题描述

我想每 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 中执行此操作的最准确方法是什么?

标签: pythonpython-3.xscheduled-tasks

解决方案


你可以使用一个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在每个小时结束时小心地加上一个。您可能想考虑这将如何围绕夏令时变化进行。

建议:将所有这些逻辑移到一个类中进行清理。


推荐阅读