from apscheduler.schedulers.blocking import BlockingScheduler import datetime from apscheduler.events import EVENT_JOB_ERROR, EVENT_JOB_EXECUTED def test_1(a, b): print(a, b) def test_2(a, b): print('*'*16) print(a) c = 0 # 修改c的值,结束异常 if datetime.datetime(2020, 5, 26, 17, 19, 30) < datetime.datetime.now(): c = 1 print(b/c) def job_listener(Event): job = sched.get_job(Event.job_id) args = job.args # 正常结束任务 if not Event.exception: # 恢复原先的任务定时时间 sched.reschedule_job(Event.job_id, trigger='cron', hour='00', minute='10', second='00') print('*'*20,'成功', '*'*20) for job in sched.get_jobs(): print(job.name) print(job.trigger) else: # 计算当前时间5秒后的时间 next_datetime = datetime.datetime.now() + datetime.timedelta(seconds=5) # 修改出现异常的任务的定时,重新计算下次执行时间,本例为5秒后 sched.reschedule_job(Event.job_id, trigger='cron', hour=next_datetime.hour, minute=next_datetime.minute, second=next_datetime.second) msg = f"jobname={job.name}|jobtrigger={job.trigger}|errcode={Event.code}|exception=[{Event.exception}]|traceback=[{Event.traceback}]|scheduled_time={Event.scheduled_run_time}" if __name__ == "__main__": service = 1 seach_date_list = 2 job_defaults = { 'coalesce': True, # 允许合并任务 'max_instances': 3 } # 创建定时任务实例 sched = BlockingScheduler() sched.configure(job_defaults=job_defaults) # 添加任务1 sched.add_job(test_1,args=(service, seach_date_list,), trigger='cron', hour='14', minute='37', second='00', id="out_warehouse_order") # 添加任务2 sched.add_job(test_2,args=(service, seach_date_list,), trigger='cron', hour='17', minute='19', second='00', id='sale_after') # 创建监听,任务出错和任务正常结束都会执行job_listener函数 sched.add_listener(job_listener, EVENT_JOB_ERROR | EVENT_JOB_EXECUTED) # 开始定时任务 sched.start()