1. 程式人生 > >springBoot整合Quartz案例

springBoot整合Quartz案例

現在有很多工排程框架,比如Jfinal-Quartz、elastic-job、EasySchedule 、Quartz 等,最常用的就是Quartz 和elastic-job,這兩個框架各有各的好處,Quartz 可以滿足複雜的任務排程,並且spring框架對Quartz也有非常好的支援,而elastic-job有elastic-job-console這個控制檯,非常方便去排程任務,比如暫停,生效,隨時修改job執行時間等。下面是springBoot整合Quartz的小案例(僅供參考)

具體步驟
1、springBoot啟動之後,讀取資料庫中配置的任務;
2、根據資料庫配置的任務名、具體類名,執行時間建立任務;
3、加入排程容器,最後啟動容器排程任務。

1、引入jar包

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.1.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.cn.dl</groupId>
	<artifactId>springbootquartz</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>
	<name>springbootquartz</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</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.3.0</version>
		</dependency>

		<dependency>
			<groupId>org.quartz-scheduler</groupId>
			<artifactId>quartz-jobs</artifactId>
			<version>2.3.0</version>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.46</version>
		</dependency>
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>1.1.9</version>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
		</dependency>
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>1.3.1</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>

2、TaskJobBean

package com.cn.dl.bean;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * Created by yanshao on 2018/12/11.
 */
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class TaskJobBean {
    //todo 實際開發還有很多屬性!!!
    private String jobName;
    private String jobClassName;
    private String jobCron;
}

3、建立表並插入三條資料

CREATE TABLE task_job_schedule (
  id bigint(20) NOT NULL AUTO_INCREMENT COMMENT '自增id',
  job_name varchar(64) COLLATE utf8mb4_bin NOT NULL DEFAULT '' COMMENT '任務名',
  job_class_name varchar(256) COLLATE utf8mb4_bin NOT NULL DEFAULT '' COMMENT '任務類名',
  job_cron varchar(32) COLLATE utf8mb4_bin NOT NULL DEFAULT '' COMMENT 'cron表示式,執行時間',
  dt_create datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '建立時間',
  dt_update datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '更新時間',
  PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT='任務排程表'

insert into task_job_schedule (id, job_name, job_class_name, job_cron, dt_create, dt_update) values('1','jobA','com.cn.dl.task.JobA','0/5 * * * * ? *','2018-12-11 11:34:25','2018-12-11 11:34:25');
insert into task_job_schedule (id, job_name, job_class_name, job_cron, dt_create, dt_update) values('2','jobB','com.cn.dl.task.JobB','0 0 04 * * ? *','2018-12-11 11:34:29','2018-12-11 11:34:29');
insert into task_job_schedule (id, job_name, job_class_name, job_cron, dt_create, dt_update) values('3','jobC','com.cn.dl.task.JobC','0/30 * * * * ? *','2018-12-11 11:34:44','2018-12-11 11:34:44');

4、TaskJobMapper

package com.cn.dl.mapper;

import com.cn.dl.bean.TaskJobBean;
import org.apache.ibatis.annotations.*;

import java.util.List;

/**
 * Created by yanshao on 2018/12/11.
 */
@Mapper
public interface TaskJobMapper {
    @Select("select job_name,job_class_name,job_cron from task_job_schedule")
    List<TaskJobBean> findAllTaskJob();
}

5、InitTaskJobConfig 

package com.cn.dl.config;

import com.cn.dl.bean.TaskJobBean;
import com.cn.dl.mapper.TaskJobMapper;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.impl.triggers.CronTriggerImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * Created by yanshao on 2018/12/11.
 */
@Component
@Order(value = 2)
@Slf4j
public class InitTaskJobConfig implements CommandLineRunner {
    @Autowired
    TaskJobMapper taskJobMapper;
    @Override
    public void run(String... strings) throws Exception {

        //讀取所有任務
        List<TaskJobBean> list = taskJobMapper.findAllTaskJob();
        //建立排程容器
        Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
        list.stream().forEach(taskJobBean -> {
            try {
                System.out.println(taskJobBean.toString());
                //建立具體的可執行的排程程式
                JobDetail jobDetail = JobBuilder.newJob((Class<? extends Job>) Class.forName(taskJobBean.getJobClassName())).build();
                //設定排程引數
                CronTriggerImpl cronTrigger = new CronTriggerImpl();
                cronTrigger.setName(taskJobBean.getJobName());
                cronTrigger.setCronExpression(taskJobBean.getJobCron());
                //加入排程容器
                scheduler.scheduleJob(jobDetail, cronTrigger);
                //啟動
                scheduler.start();
            } catch (Exception e) {
                log.error("job 啟動異常",e);
            }
        });
    }
}

6、建立三個任務類:JobA、JobB、JobC

package com.cn.dl.task;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import java.util.Date;

/**
 * Created by yanshao on 2018/12/11.
 */
public class JobA implements Job {
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        System.out.println("JobA>>>>>>"+new Date());
    }
}

其它兩個類類似JobA

7、application.properties

#redis
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=tiger

#mybatis
#開啟mybatis駝峰命名,這樣可以將mysql中帶有下劃線的對映成駝峰命名的欄位
mybatis.configuration.map-underscore-to-camel-case=true

#datasource
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/tiger_base?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&autoReconnect=true&generateSimpleParameterMetadata=true
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.max-idle=10
spring.datasource.max-wait=60000
spring.datasource.min-idle=5
spring.datasource.initial-size=5
spring.datasource.validationQuery=select 'x'

8、啟動SpringbootquartzApplication看結果:三個job都按照配置的排程時間執行

TaskJobBean(jobName=jobA, jobClassName=com.cn.dl.task.JobA, jobCron=0/5 * * * * ? *)
2018-12-11 14:04:46.168  INFO 41948 --- [           main] org.quartz.core.QuartzScheduler          : Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED started.
TaskJobBean(jobName=jobB, jobClassName=com.cn.dl.task.JobB, jobCron=0 0 04 * * ? *)
2018-12-11 14:04:46.170  INFO 41948 --- [           main] org.quartz.core.QuartzScheduler          : Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED started.
TaskJobBean(jobName=jobC, jobClassName=com.cn.dl.task.JobC, jobCron=0/30 * * * * ? *)
2018-12-11 14:04:46.172  INFO 41948 --- [           main] org.quartz.core.QuartzScheduler          : Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED started.
JobA>>>>>>Tue Dec 11 14:04:50 CST 2018
JobA>>>>>>Tue Dec 11 14:04:55 CST 2018
JobA>>>>>>Tue Dec 11 14:05:00 CST 2018
JobC>>>>>>Tue Dec 11 14:05:00 CST 2018
JobA>>>>>>Tue Dec 11 14:05:05 CST 2018
JobA>>>>>>Tue Dec 11 14:05:10 CST 2018
JobA>>>>>>Tue Dec 11 14:05:15 CST 2018
JobA>>>>>>Tue Dec 11 14:05:20 CST 2018
JobA>>>>>>Tue Dec 11 14:05:25 CST 2018
JobA>>>>>>Tue Dec 11 14:05:30 CST 2018
JobC>>>>>>Tue Dec 11 14:05:30 CST 2018
JobA>>>>>>Tue Dec 11 14:05:35 CST 2018
JobA>>>>>>Tue Dec 11 14:05:40 CST 2018
JobA>>>>>>Tue Dec 11 14:05:45 CST 2018

以上就是springBoot和Quartz整合的小案例,裡面還有很多細節問題需要注意(不能共享我們實際生產的原始碼,請見諒),但是大體流程還是可以借鑑的,畢竟經過實踐驗證。