SpringBoot 2.x Sets quartz's overwriteExistingJobs parameter

Keywords: Java SpringBoot Attribute Database

background
quartz AutoConfiguration is integrated into springBoot 2.x, but the configuration attribute provided by springBoot does not provide the setting of overwriteExistingJobs.

The resulting problems
Suppose we use quartz's own database to persist tasks and the system does not provide an interface for tasks. When we need to modify the task, change the information in the code or configuration file, such as parameters, corn expression, etc., we will find that the new expression does not work (because we did not set the overwrite ExistingJobs parameter)

Solution
After quartz automatic initialization, we get the Scheduler Factory, set the overwrite ExistingJobs parameter, and then get the Scheduler, and reset all Trigger s through Scheduler.

code implementation

package com.koolyun.eas.account.scheduler.config;

import org.quartz.*;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.boot.autoconfigure.quartz.QuartzAutoConfiguration;
import org.springframework.boot.autoconfigure.quartz.QuartzProperties;
import org.springframework.boot.autoconfigure.quartz.SchedulerFactoryBeanCustomizer;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;

/**
 * @author bozheng
 * @date 2018/10/10 15:48
 */
@Configuration
@AutoConfigureAfter(QuartzAutoConfiguration.class)
public class QuartzSupportConfig{

    private final Trigger[] triggers;

    public QuartzSupportConfig(Trigger[] triggers){
        this.triggers = triggers;
    }

    @Autowired
    SchedulerFactoryBean schedulerFactoryBean;

    @PostConstruct
    public void quartzScheduler() throws SchedulerException {
        schedulerFactoryBean.setOverwriteExistingJobs(true);
        Scheduler scheduler = schedulerFactoryBean.getScheduler();
        for (Trigger trigger : triggers){
            scheduler.rescheduleJob(trigger.getKey(),trigger);
        }
    }

}

Posted by NickG21 on Sun, 03 Feb 2019 12:33:15 -0800