解决方法
添加配置:
max_instances
:添加最多可同时进行的数量
misfire_grace_time
:如果意外断开,多少秒以内会重新尝试运行
如:
scheduler.add_job(print_each_5_second, 'interval', seconds=5, max_instances=10, misfire_grace_time=10)
问题解析
假如我们运行如下代码:
from datetime import datetime
from apscheduler.schedulers.background import BlockingSchedulerdef print_each_second():"""自动化:每1秒"""print(f"=== 自动化每1秒:{datetime.now()} ===")def main():print("============================ 启动 自动化 ============================")scheduler = BlockingScheduler()scheduler.add_job(print_each_second, 'interval', seconds=1)scheduler.start()if __name__ == '__main__':main()
可以得到如下结果:
============================ 启动 自动化 ============================
=== 自动化每1秒:2023-09-26 14:52:47.216362 ===
=== 自动化每1秒:2023-09-26 14:52:48.220016 ===
=== 自动化每1秒:2023-09-26 14:52:49.228359 ===
=== 自动化每1秒:2023-09-26 14:52:50.212165 ===
但对于如下程序:
from datetime import datetime
from apscheduler.schedulers.background import BlockingScheduler
import timedef print_each_5_second():"""自动化:每5秒"""print(f"=== 初始执行:{datetime.now()} ===")time.sleep(6)print(f"=== 结束输出等待6秒:{datetime.now()} ===")def main():print("============================ 启动 自动化 ============================")scheduler = BlockingScheduler()scheduler.add_job(print_each_5_second, 'interval', seconds=5, max_instances=10, misfire_grace_time=10)scheduler.start()if __name__ == '__main__':main()
对应的结果就是:
============================ 启动 自动化 ============================
=== 初始执行:2023-09-26 15:20:24.520201 ===
=== 初始执行:2023-09-26 15:20:29.525392 ===
=== 结束输出等待6秒:2023-09-26 15:20:30.526067 ===
=== 初始执行:2023-09-26 15:20:34.517294 ===
=== 结束输出等待6秒:2023-09-26 15:20:35.533115 ===
=== 初始执行:2023-09-26 15:20:39.523247 ===
=== 结束输出等待6秒:2023-09-26 15:20:40.520940 ===
=== 初始执行:2023-09-26 15:20:44.525985 ===
观察可知:同时执行的程序出现了,一旦时间到了启动任务的时间,会新建一个任务启动执行程序