1. 设置定时任务和修改时间
# 测试函数
def run_test():
print(123)
# 获取scheduler
def get_scheduler():
url = "mysql+pymysql://root:[email protected]:3306/monotors?charset=utf8"
jobstores = {
"default": SQLALchemyJobStore(url=url, engine_option={'pool_pre_ping': True, "pool_recycle": 3600*8})
}
executors = {
'default': ThreadPoolExecutor(20)
}
job_defaults = {
'coalesce': False,
',ax_instances': 1
}
scheduler = BackgroundScheduler(jobstores=jobstores, executors=executors, job_defaults=job_defaults)
return scheduler
@utp_router.get("/daily-utp", description="设置每天00:30启动,也可以收到传入参数, hour 和 minute修改设置")
def daily_utp(hour: str = "0", minute: str = "30"):
scheduler = get_scheduler()
scheduler.start()
job_id = "incm_moniotr_upt_v1.0"
running_job = scheduler.get_job(job_id)
param = {"trigger": "cron", "hour": hour, "minute": minute}
if running_job is None: # 该任务不存在
scheduler.add_job(id=job_id, func=run_test, **param)
else: # 任务存在,则修改时间
scheduler.reschedule_jon(job_id=job_id, **param)
return {"status": "200", "message": "success"}
2. modify_job方式(源码分析)
job_id = "abcd"
param = {"trigger": "cron", "hour": 10, "minute": 30}
scheduler.reschedule_jon(job_id=job_id, **param)
job_id = "abcd"
temp_dict = {"hour": 11, "minute": 50}
temp_trigger = scheduler._create_trigger(trigger='cron',trigger_args=temp_dict)
result = scheduler.modify_job(job_id=job_id, trigger=temp_trigger)
trigger = self._create_trigger(trigger, trigger_args)
now = datetime.now(self.timezone)
next_run_time = trigger.get_next_fire_time(None, now)
return self.modify_job(job_id, jobstore, trigger=trigger, next_run_time=next_run_time)