如何用Python创建后台线程运行schedule定时任务并配置参数
问题根源
你代码没有生效的核心原因是主线程只等待了10秒就调用stop_run_continuously.set()终止了后台调度线程,程序直接退出了,根本等不到17:00的执行时间点。
参数说明
run_continuously的interval参数:这个是后台调度线程每次检查是否有到期任务的间隔时间,单位是秒。你是每天执行一次的任务,这个值设1~60秒都可以,设1秒的话最多误差1秒,设60秒最多误差1分钟,对按天执行的任务来说完全没影响,默认1秒就够用。- 主线程里的
time.sleep():你原来写的10秒完全不足以支撑到任务执行时间,如果要让调度任务一直后台运行,就不能主动终止调度线程,需要让主线程一直保持运行状态。
修正后代码
import threading import time import schedule def run_continuously(interval=1): """Continuously run, while executing pending jobs at each elapsed time interval. @return cease_continuous_run: threading. Event which can be set to cease continuous run. Please note that it is *intended behavior that run_continuously() does not run missed jobs*. For example, if you've registered a job that should run every minute and you set a continuous run interval of one hour then your job won't be run 60 times at each interval but only once. """ cease_continuous_run = threading.Event() class ScheduleThread(threading.Thread): @classmethod def run(cls): while not cease_continuous_run.is_set(): schedule.run_pending() time.sleep(interval) continuous_thread = ScheduleThread() # 设为守护线程,主线程退出时自动销毁 continuous_thread.daemon = True continuous_thread.start() return cease_continuous_run def background_job(): exec(open('/Users/filename.py').read()) schedule.every().day.at("17:00").do(background_job) # 启动后台线程 stop_run_continuously = run_continuously() # 主线程一直阻塞不退出,保持后台调度运行 while True: time.sleep(3600)
额外注意事项
- 如果需要程序真正在系统后台脱离终端运行,Linux/macOS下可以直接用
nohup python 你的脚本名.py &启动,Windows下可以把脚本打包成后台服务运行。 - 用
exec执行外部py文件不是最优写法,你也可以把filename.py的逻辑封装成函数,直接导入调用更稳定。
内容的提问来源于stack exchange,提问作者Tcs106
相关产品推荐
相关产品推荐

