springboot整合Quartz實現動態配置定時任務


 前言

 在咱們平常的開發中,不少時候,定時任務都不是寫死的,而是寫到數據庫中,從而實現定時任務的動態配置,下面就經過一個簡單的示例,來實現這個功能。前端

 1、新建一個springboot工程,並添加依賴 

<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
 
		<dependency><!-- 爲了方便測試,此處使用了內存數據庫 -->
			<groupId>com.h2database</groupId>
			<artifactId>h2</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		
		<dependency>
			<groupId>org.quartz-scheduler</groupId>
			<artifactId>quartz</artifactId>
			<version>2.2.1</version>
			<exclusions>
				<exclusion>
					<artifactId>slf4j-api</artifactId>
					<groupId>org.slf4j</groupId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency><!-- 該依賴必加,裏面有sping對schedule的支持 -->
                       <groupId>org.springframework</groupId>
                       <artifactId>spring-context-support</artifactId>
        </dependency> 複製代碼

2、配置文件application.properties 

# 服務器端口號 
server.port=7902
# 是否生成ddl語句 
spring.jpa.generate-ddl=false  
# 是否打印sql語句 
spring.jpa.show-sql=true  
# 自動生成ddl,因爲指定了具體的ddl,此處設置爲none 
spring.jpa.hibernate.ddl-auto=none  
# 使用H2數據庫 
spring.datasource.platform=h2  
# 指定生成數據庫的schema文件位置 
spring.datasource.schema=classpath:schema.sql  
# 指定插入數據庫語句的腳本位置 
spring.datasource.data=classpath:data.sql  
# 配置日誌打印信息 
logging.level.root=INFO  
logging.level.org.hibernate=INFO  
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE  
logging.level.org.hibernate.type.descriptor.sql.BasicExtractor=TRACE  
logging.level.com.itmuch=DEBUG複製代碼

 3、Entity類 

package com.chhliu.springboot.quartz.entity;
 
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
 
@Entity
public class Config {
	@Id
	  @GeneratedValue(strategy = GenerationType.AUTO)
	  private Long id;
 
	  @Column
	  private String cron;
 
	/**
	 * @return the id
	 */
	public Long getId() {
		return id;
	}
        ……此處省略getter和setter方法……
} 複製代碼

4、任務類

package com.chhliu.springboot.quartz.entity;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Component;
 
@Configuration
@Component // 此註解必加
@EnableScheduling // 此註解必加
public class ScheduleTask {
	private static final Logger LOGGER =  LoggerFactory.getLogger(ScheduleTask.class);
	public void sayHello(){
		LOGGER.info("Hello world, i'm the king of the world!!!");
	}
}複製代碼

 5、Quartz配置類 

因爲springboot追求零xml配置,因此下面會以配置Bean的方式來實現 java

 package com.chhliu.springboot.quartz.entity;spring

import org.quartz.Trigger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
import org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
 
@Configuration
public class QuartzConfigration {
    /**
     * attention:
     * Details:配置定時任務
     */
    @Bean(name = "jobDetail")
    public MethodInvokingJobDetailFactoryBean detailFactoryBean(ScheduleTask task) {// ScheduleTask爲須要執行的任務
        MethodInvokingJobDetailFactoryBean jobDetail = new MethodInvokingJobDetailFactoryBean();
        /*
         *  是否併發執行
         *  例如每5s執行一次任務,可是當前任務尚未執行完,就已通過了5s了,
         *  若是此處爲true,則下一個任務會執行,若是此處爲false,則下一個任務會等待上一個任務執行完後,再開始執行
         */
        jobDetail.setConcurrent(false);
        
        jobDetail.setName("srd-chhliu");// 設置任務的名字
        jobDetail.setGroup("srd");// 設置任務的分組,這些屬性均可以存儲在數據庫中,在多任務的時候使用
        
        /*
         * 爲須要執行的實體類對應的對象
         */
        jobDetail.setTargetObject(task);
        
        /*
         * sayHello爲須要執行的方法
         * 經過這幾個配置,告訴JobDetailFactoryBean咱們須要執行定時執行ScheduleTask類中的sayHello方法
         */
        jobDetail.setTargetMethod("sayHello");
        return jobDetail;
    }
    
    /**
     * attention:
     * Details:配置定時任務的觸發器,也就是何時觸發執行定時任務
     */
    @Bean(name = "jobTrigger")
    public CronTriggerFactoryBean cronJobTrigger(MethodInvokingJobDetailFactoryBean jobDetail) {
        CronTriggerFactoryBean tigger = new CronTriggerFactoryBean();
        tigger.setJobDetail(jobDetail.getObject());
        tigger.setCronExpression("0 30 20 * * ?");// 初始時的cron表達式
        tigger.setName("srd-chhliu");// trigger的name
        return tigger;
 
    }
 
    /**
     * attention:
     * Details:定義quartz調度工廠
     */
    @Bean(name = "scheduler")
    public SchedulerFactoryBean schedulerFactory(Trigger cronJobTrigger) {
        SchedulerFactoryBean bean = new SchedulerFactoryBean();
        // 用於quartz集羣,QuartzScheduler 啓動時更新己存在的Job
        bean.setOverwriteExistingJobs(true);
        // 延時啓動,應用啓動1秒後
        bean.setStartupDelay(1);
        // 註冊觸發器
        bean.setTriggers(cronJobTrigger);
        return bean;
    }
}複製代碼

 6、定時查庫,並更新任務

package com.chhliu.springboot.quartz.entity;
 
import javax.annotation.Resource;
 
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
 
import com.chhliu.springboot.quartz.repository.ConfigRepository;
 
@Configuration
@EnableScheduling
@Component
public class ScheduleRefreshDatabase {
	@Autowired
	private ConfigRepository repository;
 
	@Resource(name = "jobDetail")
	private JobDetail jobDetail;
 
	@Resource(name = "jobTrigger")
	private CronTrigger cronTrigger;
 
	@Resource(name = "scheduler")
	private Scheduler scheduler;
 
	@Scheduled(fixedRate = 5000) // 每隔5s查庫,並根據查詢結果決定是否從新設置定時任務
	public void scheduleUpdateCronTrigger() throws SchedulerException {
		CronTrigger trigger = (CronTrigger) scheduler.getTrigger(cronTrigger.getKey());
		String currentCron = trigger.getCronExpression();// 當前Trigger使用的
		String searchCron = repository.findOne(1L).getCron();// 從數據庫查詢出來的
		System.out.println(currentCron);
		System.out.println(searchCron);
		if (currentCron.equals(searchCron)) {
			// 若是當前使用的cron表達式和從數據庫中查詢出來的cron表達式一致,則不刷新任務
		} else {
			// 表達式調度構建器
			CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(searchCron);
			// 按新的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 = searchCron;
		}
	}
}
複製代碼

7、相關腳本

 一、data.sqlsql

insert into config(id,cron) values(1,'0 0/2 * * * ?'); # 每2分鐘執行一次定時任務複製代碼

 二、schema.sql 數據庫

drop table config if exists;
create table config(
	id bigint generated by default as identity,
	cron varchar(40),
	primary key(id)
);複製代碼

 8、運行測試 測試結果以下:

(Quartz默認的線程池大小爲10)api

0 30 20 * * ?
0 0/2 * * * ?
2017-03-08 18:02:00.025  INFO 5328 --- [eduler_Worker-1] c.c.s.quartz.entity.ScheduleTask         : Hello world, i'm the king of the world!!! 2017-03-08 18:04:00.003 INFO 5328 --- [eduler_Worker-2] c.c.s.quartz.entity.ScheduleTask : Hello world, i'm the king of the world!!!
2017-03-08 18:06:00.002  INFO 5328 --- [eduler_Worker-3] c.c.s.quartz.entity.ScheduleTask         : Hello world, i'm the king of the world!!! 2017-03-08 18:08:00.002 INFO 5328 --- [eduler_Worker-4] c.c.s.quartz.entity.ScheduleTask : Hello world, i'm the king of the world!!!
複製代碼

從上面的日誌打印時間來看,咱們實現了動態配置,最初的時候,任務是天天20:30執行,後面經過動態刷新變成了每隔2分鐘執行一次。springboot

 雖然上面的解決方案沒有使用Quartz推薦的方式完美,但基本上能夠知足咱們的需求,固然也能夠採用觸發事件的方式來實現,例如當前端修改定時任務的觸發時間時,異步的向後臺發送通知,後臺收到通知後,而後再更新程序,也能夠實現動態的定時任務刷新 bash

原文連接:https://blog.csdn.net/liuchuanhong1/article/details/60873295  
服務器

相關文章
相關標籤/搜索