liangcmwn / docs

mydocs on git
0 stars 0 forks source link

Spring 集成 Quartz #3

Open liangcmwn opened 5 years ago

liangcmwn commented 5 years ago

1. pom.xml引入Quartz

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-quartz</artifactId>
</dependency>

编写Job

Job可以定义为Spring Bean,注入依赖,executeInternal中执行具体业务逻辑

@Slf4j
@Component
public class ExampleJob extends QuartzJobBean {

    private ExampleDao exampleDao;

    @Autowired
    public ExampleJob (ExampleDao exampleDao) {
        this.exampleDao= exampleDao;
    }

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
    }
}

启动Job

@Configuration
public class QuartzScheduleConfiguration {

    private String group = "group1";

    private TriggerKey triggerKey = TriggerKey.triggerKey("CronTrigger1", group );

    private JobKey jobKey = JobKey.jobKey("cronJob1", group );

    @Autowired
    private Scheduler scheduler;

    @Bean
    public Object startJobs() throws SchedulerException {
        //每次启动前检查是否存在-如果不存在就启动Job
        //也可以在配置文件中设置每次启动时覆盖配置
//        spring.quartz.overwrite-existing-jobs
        if (!scheduler.checkExists(triggerKey )) {
            scheduler.scheduleJob(newJobDetail(ExampleJob .class, jobKey ),
                    newCronTrigger(triggerKey , "0/10 * * * * ?"));
        } else {
            updateCron(triggerKey , "0/10 * * * * ?");
        }
        return new Object();
    }

    /**
     * 判断cron是否有修改,如果有修改,更新Trigger
     */
    private void updateCron(TriggerKey key, String cronToUpdate) throws SchedulerException {
        CronTrigger trigger = (CronTrigger) scheduler.getTrigger(key);
        if(! cronToUpdate.equalsIgnoreCase(trigger.getCronExpression())) {
            scheduler.rescheduleJob(key, newCronTrigger(key, cronToUpdate));
        }
    }

    public JobDetail newJobDetail(Class clazz, JobKey jobKey) {
        JobDetail jobDetail = JobBuilder.newJob(clazz)
                // 定义name/group
                .withIdentity(jobKey)
                .build();
        return jobDetail;
    }

    /**
     * 定时触发器
     *
     * @return
     */
    public Trigger newCronTrigger(TriggerKey key, String cron) {
        // 定义一个Trigger
        TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();
        // 定义name/group
        triggerBuilder.withIdentity(key);
        triggerBuilder.startNow();// 一旦加入scheduler,立即生效
        triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(cron));
        Trigger trigger = triggerBuilder.build();
        return trigger;
    }

}

配置文件

spring:
  quartz:
    job-store-type: jdbc
#    overwrite-existing-jobs: true
    jdbc:
      initialize-schema: never
    properties:
      org.quartz.jobStore.isClustered: true
      org.quartz.scheduler.instanceId: AUTO