packagecom.jdkeji.shares.quartz;importjavax.annotation.Resource;importorg.mybatis.spring.SqlSessionTemplate;importorg.quartz.CronScheduleBuilder;importorg.quartz.CronTrigger;importorg.quartz.JobDetail;importorg.quartz.Scheduler;importorg.quartz.SchedulerException;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.context.annotation.Configuration;importorg.springframework.scheduling.annotation.EnableScheduling;importorg.springframework.scheduling.annotation.Scheduled;importorg.springframework.stereotype.Component;importcom.jdkeji.shares.config.model.BusinessConfig;
@Configuration
@EnableScheduling
@Componentpublic classScheduleRefreshDatabase {
@AutowiredprivateSqlSessionTemplate st;
@Resource(name= "jobDetail")privateJobDetail jobDetail;
@Resource(name= "jobTrigger")privateCronTrigger cronTrigger;
@Resource(name= "schedulerTwo")privateScheduler scheduler;
@Scheduled(fixedRate= 5000) //每隔5s查库,并根据查询结果决定是否重新设置定时任务
public void scheduleUpdateCronTrigger() throwsSchedulerException {
CronTrigger trigger=(CronTrigger) scheduler.getTrigger(cronTrigger.getKey());
String currentCron= trigger.getCronExpression();//当前Trigger使用的
BusinessConfig bc = st.selectOne("BusinessConfig.selectByExample");
System.out.println(currentCron);
String [] date= bc.getClxg().split(":");
String cron= "0 " + date[1] + " " + date[0] + " * * ?";
System.out.println(cron);if(currentCron.equals(cron)) {//如果当前使用的cron表达式和从数据库中查询出来的cron表达式一致,则不刷新任务
} else{//表达式调度构建器
CronScheduleBuilder scheduleBuilder =CronScheduleBuilder.cronSchedule(cron);//按新的cronExpression表达式重新构建trigger
trigger =(CronTrigger) scheduler.getTrigger(cronTrigger.getKey());
trigger=trigger.getTriggerBuilder().withIdentity(cronTrigger.getKey())
.withSchedule(scheduleBuilder).build();//按新的trigger重新设置job执行
scheduler.rescheduleJob(cronTrigger.getKey(), trigger);
currentCron=cron;
}
}
}