现在有很多任务调度框架,比如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包
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.1.1.RELEASE
com.cn.dl
springbootquartz
0.0.1-SNAPSHOT
jar
springbootquartz
Demo project for Spring Boot
1.8
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
test
org.quartz-scheduler
quartz
2.3.0
org.quartz-scheduler
quartz-jobs
2.3.0
mysql
mysql-connector-java
5.1.46
com.alibaba
druid
1.1.9
org.projectlombok
lombok
org.mybatis.spring.boot
mybatis-spring-boot-starter
1.3.1
org.springframework.boot
spring-boot-maven-plugin
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 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 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整合的小案例,里面还有很多细节问题需要注意(不能共享我们实际生产的源代码,请见谅),但是大体流程还是可以借鉴的,毕竟经过实践验证。