python - 在每轮开始时运行一个函数,间隔 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 中执行此操作的最准确方法是什么?
解决方案
你可以使用一个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
在每个小时结束时小心地加上一个。您可能想考虑这将如何围绕夏令时变化进行。
建议:将所有这些逻辑移到一个类中进行清理。
推荐阅读
- php - 无法在 laravel 控制器中获取变量的值
- rabbitmq - 使用rabbiqmq cli或管理工具连接远程rabbitmq集群
- c++ - cvSaveImage 未在此范围内声明 OpenCV3.4
- python - 电子邮件、登录、注销身份验证问题
- image - 如何使用 Flutter 插件将 adobexd 方向缩放原型导出到 Flutter
- azureservicebus - 事件网格主题与事件网格系统主题
- ios - 使 iOS 14 Logger 静态化有什么缺点吗?
- html - Vue JS 动态 html v-model 绑定
- python - Python JSON 更新和删除对象的值
- c# - ASP.Net MVC 5:为基于 Web 的产品设计基于角色的访问系统的最佳方法