springBoot2.x設置quartz的overwriteExistingJobs參數

背景
springBoot2.x中集成了quartz的自動配置類(QuartzAutoConfiguration),但是springBoot提供的配置屬性中並沒有提供overwriteExistingJobs這個屬性的設置。

導致的問題
假如我們使用quartz自帶的數據庫對任務進行了持久化且系統並沒有提供對任務的界面化操作。當我們需要對任務進行修改時,更改了代碼或者配置文件中的信息,如參數、corn表達式等,會發現新的表達式並沒有生效(原因是我們沒有設置overwriteExistingJobs參數)

解決方案
在quartz自動初始化之後,我們獲取SchedulerFactory,設置overwriteExistingJobs參數,然後獲得Scheduler,通過Scheduler重新設置所有Trigger.

代碼實現

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

import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.quartz.QuartzAutoConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

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

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

    @Autowired(required = false)
    private List<Trigger> triggers ;

    @Autowired
    SchedulerFactoryBean schedulerFactoryBean;

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

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章