1. 程式人生 > >SpringBoot系列5-定時任務-springboot整合quartz實現動態定時任務

SpringBoot系列5-定時任務-springboot整合quartz實現動態定時任務

springboot有自帶的定時任務為什麼還要使用quartz

使用springboot自帶的定時任務可以很簡單很方便的完成一些簡單的定時任務,但是我們想動態的執行我們的定時任務就比較困難了。然而使用quartz卻可以很容易的管理我們的定時任務,很容易動態的操作定時任務。下面我們就講解下如何使用quartz動態實現定時任務!

首先來一張截圖看看我們的目錄結構

pom.xml引入依賴

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--quartz相關依賴-->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
<!--lombok-->
<dependency>
	<groupId>org.projectlombok</groupId>
	<artifactId>lombok</artifactId>
</dependency>

MyJob實現Job介面,重寫execute方法在裡面操作我們要執行的業務邏輯。

@Slf4j
public class MyJob implements Job {
    @Autowired
    private MyService myService;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        log.info("任務開始執行了");
        try {
            executeTask();
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        log.info("任務執行結束了");
    }

    private void executeTask() throws SchedulerException {
        myService.bizFunction();
    }
}

定義QuartzManager管理我們的定時任務方法

**
 * @author 天空藍藍的
 */
@Configuration
public class QuartzManager {

    public static final String JOB1="job1";
    public static final String GROUP1="group1";
    /**預設每個星期凌晨一點執行*/
    //public static final String DEFAULT_CRON="0 0 1 ? * L";
    /**預設5秒執行一次*/
    public static final String DEFAULT_CRON="*/5 * * * * ?";

    /**
     * 任務排程
     */
    @Autowired
    private Scheduler scheduler;

    /**
     * 開始執行定時任務
     */
    public void startJob() throws SchedulerException {
        startJobTask(scheduler);
        scheduler.start();
    }

    /**
     * 啟動定時任務
     * @param scheduler
     */
    private void startJobTask(Scheduler scheduler) throws SchedulerException {
        JobDetail jobDetail= JobBuilder.newJob(MyJob.class).withIdentity(JOB1,GROUP1).build();
        CronScheduleBuilder cronScheduleBuilder=CronScheduleBuilder.cronSchedule(DEFAULT_CRON);
        CronTrigger cronTrigger=TriggerBuilder.newTrigger().withIdentity(JOB1,GROUP1)
                .withSchedule(cronScheduleBuilder).build();
        scheduler.scheduleJob(jobDetail,cronTrigger);

    }
    /**
     * 獲取Job資訊
     * @param name
     * @param group
     */
    public String getjobInfo(String name,String group) throws SchedulerException {
        TriggerKey triggerKey=new TriggerKey(name,group);
        CronTrigger cronTrigger= (CronTrigger) scheduler.getTrigger(triggerKey);
        return String.format("time:%s,state:%s",cronTrigger.getCronExpression(),
                scheduler.getTriggerState(triggerKey).name());
    }

    /**
     * 修改任務的執行時間
     * @param name
     * @param group
     * @param cron cron表示式
     * @return
     * @throws SchedulerException
     */
    public boolean modifyJob(String name,String group,String cron) throws SchedulerException{
        Date date=null;
        TriggerKey triggerKey=new TriggerKey(name, group);
        CronTrigger cronTrigger= (CronTrigger) scheduler.getTrigger(triggerKey);
        String oldTime=cronTrigger.getCronExpression();
        if (!oldTime.equalsIgnoreCase(cron)){
            CronScheduleBuilder cronScheduleBuilder=CronScheduleBuilder.cronSchedule(cron);
            CronTrigger trigger=TriggerBuilder.newTrigger().withIdentity(name,group)
                    .withSchedule(cronScheduleBuilder).build();
            date=scheduler.rescheduleJob(triggerKey,trigger);
        }
        return date !=null;
    }

    /**
     * 暫停所有任務
     * @throws SchedulerException
     */
    public void pauseAllJob()throws SchedulerException{
        scheduler.pauseAll();
    }

    /**
     * 暫停某個任務
     * @param name
     * @param group
     * @throws SchedulerException
     */
    public void pauseJob(String name,String group)throws SchedulerException{
        JobKey jobKey=new JobKey(name,group);
        JobDetail jobDetail=scheduler.getJobDetail(jobKey);
        if (jobDetail==null)
            return;
        scheduler.pauseJob(jobKey);
    }

    /**
     * 恢復所有任務
     * @throws SchedulerException
     */
    public void resumeAllJob()throws SchedulerException{
        scheduler.resumeAll();
    }
    /**
     * 恢復某個任務
     */
    public void resumeJob(String name,String group)throws SchedulerException{
        JobKey jobKey=new JobKey(name,group);
        JobDetail jobDetail=scheduler.getJobDetail(jobKey);
        if (jobDetail==null)
            return;
        scheduler.resumeJob(jobKey);
    }

    /**
     * 刪除某個任務
     * @param name
     * @param group
     * @throws SchedulerException
     */
    public void deleteJob(String name,String group)throws SchedulerException{
        JobKey jobKey=new JobKey(name, group);
        JobDetail jobDetail=scheduler.getJobDetail(jobKey);
        if (jobDetail==null)
            return;
        scheduler.deleteJob(jobKey);
    }

}

定義ApplicationStartQuartzJobListener實現當應用啟動,或重新整理時,啟動我們的定時任務

/**
 * @author 天空藍藍的
 */
@Slf4j
@Configuration
public class ApplicationStartQuartzJobListener implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private QuartzManager quartzManager;


    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        try {
            quartzManager.startJob();
            log.info("任務已經啟動......");
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }
    /**
     * 初始注入scheduler
     */
    @Bean
    public Scheduler scheduler() throws SchedulerException{
        SchedulerFactory schedulerFactoryBean = new StdSchedulerFactory();
        return schedulerFactoryBean.getScheduler();
    }
}

定義MyJobFactory建立Quartz例項


/**
 * @author 天空藍藍的
 */
@Component
public class MyJobFactory extends AdaptableJobFactory{
    @Autowired
    private AutowireCapableBeanFactory capableBeanFactory;

    @Override
    protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
        // 呼叫父類的方法
        Object jobInstance = super.createJobInstance(bundle);
        // 進行注入
        capableBeanFactory.autowireBean(jobInstance);
        return jobInstance;
    }
}

Application如何類Start注入MyJobFactory和Scheduler


/**
 * @author 天空藍藍的
 */
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
@Configuration
public class Start {

	public static void main(String[] args) {
		SpringApplication.run(Start.class, args);
	}

	@Autowired
	private MyJobFactory myJobFactory;

	@Bean
	public SchedulerFactoryBean schedulerFactoryBean() {
		SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
		schedulerFactoryBean.setJobFactory(myJobFactory);
		System.out.println("myJobFactory:"+myJobFactory);
		return schedulerFactoryBean;
	}
	@Bean
	public Scheduler scheduler() {
		return schedulerFactoryBean().getScheduler();
	}
}

定義ModifyCronController動態修改定時任務

/**
 * @author 天空藍藍的
 */
@RestController
public class ModifyCronController {

    @Autowired
    private QuartzManager quartzManager;
    @GetMapping("modify")
    public String modify() throws SchedulerException {
        /**10秒執行一次*/
        String cron="*/10 * * * * ?";
        quartzManager.pauseJob(QuartzManager.JOB1,QuartzManager.GROUP1);
        quartzManager.modifyJob(QuartzManager.JOB1,QuartzManager.GROUP1,cron);
        return "ok";
    }
}

瀏覽器訪問http://localhost:8080/modify我們可以看到將預設的5秒執行一次任務動態變成了10秒執行一次了