1.使用quartz
1.1 pom.xml
1 <?xml version="1.0" encoding="UTF-8"?>
2
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
5 4.0.0
6
7 com.quartz
8 quartz
9 1.0-SNAPSHOT
10
11
12
13
14 org.quartz-scheduler
15 quartz
16 2.2.1
17
18
19 org.springframework
20 spring-context-support
21 4.3.13.RELEASE
22
23
24
25
1.2 RAMJob.class
1 packagecom.quartz.ram;2
3 importorg.quartz.Job;4 importorg.quartz.JobExecutionContext;5 importorg.quartz.JobExecutionException;6 importorg.slf4j.Logger;7 importorg.slf4j.LoggerFactory;8
9 importjava.util.Date;10
11 public class RAMJob implementsJob {12
13 private static Logger _log = LoggerFactory.getLogger(RAMJob.class);14
15 //@Override
16 public void execute(JobExecutionContext arg0) throwsJobExecutionException {17 System.out.println("执行定时任务");18 _log.info("Say hello to Quartz" + newDate());19 }20
21 }
1.3 RAMQuartz.class
1 packagecom.quartz.QuartzTest;2
3 importcom.quartz.ram.RAMJob;4 import org.quartz.*;5 importorg.quartz.impl.StdSchedulerFactory;6 importorg.slf4j.Logger;7 importorg.slf4j.LoggerFactory;8
9 importjava.util.Date;10
11 /**
12 * This is a RAM Store Quartz!13 *14 *@authordufy15 * @date 2017.02.0416 */
17 public classRAMQuartz {18
19 private static Logger _log = LoggerFactory.getLogger(RAMQuartz.class);20
21 public static void main(String[] args) throwsSchedulerException {22 //1.创建Scheduler的工厂
23 SchedulerFactory sf = newStdSchedulerFactory();24 //2.从工厂中获取调度器实例
25 Scheduler scheduler =sf.getScheduler();26
27
28 //3.创建JobDetail
29 JobDetail jb = JobBuilder.newJob(RAMJob.class)30 .withDescription("this is a ram job") //job的描述
31 .withIdentity("ramJob", "ramGroup") //job 的name和group
32 .build();33
34 //任务运行的时间,SimpleSchedle类型触发器有效
35 long time = System.currentTimeMillis() + 3 * 1000L; //3秒后启动任务
36 Date statTime = newDate(time);37
38 //4.创建Trigger39 //使用SimpleScheduleBuilder或者CronScheduleBuilder
40 Trigger t =TriggerBuilder.newTrigger()41 .withDescription("")42 .withIdentity("ramTrigger", "ramTriggerGroup")43 //.withSchedule(SimpleScheduleBuilder.simpleSchedule())
44 .startAt(statTime) //默认当前时间启动
45 .withSchedule(CronScheduleBuilder.cronSchedule("0/2 * * * * ?")) //两秒执行一次
46 .build();47
48 //5.注册任务和定时器
49 scheduler.scheduleJob(jb, t);50
51 //6.启动 调度器
52 scheduler.start();53 _log.info("启动时间 : " + newDate());54
55 }56 }
1.4 使用方法启动RAMQuartz.class
2.springboot-quartz springboot结合quartz完成定时任务
2.1 项目结构
2.2 springboot-quartz pom.xml
1 <?xml version="1.0" encoding="UTF-8"?>
2
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
5 4.0.0
6
7 com.springboot.quartz
8 springboot-quartz
9 pom
10 1.0-SNAPSHOT
11
12 springboot-quartz-api
13 springboot-quartz-model
14 springboot-quartz-service
15
16
17
18
19 org.springframework.boot
20 spring-boot-starter-parent
21 1.4.1.RELEASE
22
23
24
25
26
27 org.springframework.boot
28 spring-boot-maven-plugin
29
30
31
32 repackage
33
34
35
36
37 true
38
39
40
41
42
43
2.3 springboot-quartz-model模块结构
2.3.1 pom.xml
1 <?xml version="1.0" encoding="UTF-8"?>
2
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
5
6 springboot-quartz
7 com.springboot.quartz
8 1.0-SNAPSHOT
9
10 4.0.0
11
12 springboot-quartz-model
13
14
15
16 org.springframework.boot
17 spring-boot-starter-data-jpa
18
19
20 org.projectlombok
21 lombok
22 1.16.18
23
24
25
26
2.3.2 TimesConfig.class
1 packagecom.springboot.quartz.model;2
3 importlombok.Data;4 importorg.hibernate.annotations.GenericGenerator;5
6 import javax.persistence.*;7 importjava.io.Serializable;8 importjava.util.Date;9
10 @Entity11 @Data12 public class TimesConfig implementsSerializable {13
14 /**
15 * 主键16 */
17 @Id18 @GenericGenerator(name = "PKUUID", strategy = "uuid2")19 @GeneratedValue(generator = "PKUUID")20 @Column(columnDefinition = "varchar(255) comment '主键'")21 privateString id;22
23 /**
24 * 触发器Cron代码25 */
26 @Column(columnDefinition = "varchar(255) comment '触发器Cron代码'")27 privateString cron;28
29 /**
30 * 创建日期31 */
32 @Column(columnDefinition = "timestamp comment '创建日期'")33 privateDate dateCreated;34
35 /**
36 * 最后更新日期37 */
38 @Column(columnDefinition = "timestamp comment '最后更新日期'")39 privateDate lastUpdated;40
41 /**
42 * 删除日期43 */
44 @Column(columnDefinition = "timestamp comment '删除日期'")45 privateDate deleteDate;46
47 /**
48 * 删除标记49 */
50 @Column(columnDefinition = "int(1) comment '删除标记'")51 private Boolean isDelete = false;52
53 @PrePersist54 protected voidprePersist() {55 dateCreated = newDate();56 }57
58 }
2.3.3 TimesConfigRepository.class
1 packagecom.springboot.quartz.repository;2
3 importcom.springboot.quartz.model.TimesConfig;4 importorg.springframework.data.jpa.repository.JpaRepository;5
6 importjava.util.List;7
8 /**
9 *@authorluoxianwei10 * @date 2018/6/311 */
12 public interface TimesConfigRepository extends JpaRepository{13
14 ListfindByIsDelete(Boolean isDelete);15
16 TimesConfig findByIdAndIsDelete(String id, Boolean isDelete);17
18 }
2.4 springboot-quartz-api 模块结构
2.4.1 pom.xml
1 <?xml version="1.0" encoding="UTF-8"?>
2
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
5
6 springboot-quartz
7 com.springboot.quartz
8 1.0-SNAPSHOT
9
10 4.0.0
11
12 springboot-quartz-api
13
14
15 org.projectlombok
16 lombok
17 1.16.18
18
19
20
21
2.4.2 TimesConfigDto.class
1 packagecom.springboot.quartz.dto;2
3 importlombok.Data;4
5 importjava.io.Serializable;6 importjava.util.Date;7
8 /**
9 *@authorluoxianwei10 * @date 2018/6/311 */
12 @Data13 public class TimesConfigDto implementsSerializable {14
15 /**
16 * 主键17 */
18 privateString id;19
20 /**
21 * 触发器Cron代码22 */
23 privateString cron;24
25 /**
26 * 创建日期27 */
28 privateDate dateCreated;29
30 /**
31 * 最后更新日期32 */
33 privateDate lastUpdated;34
35 /**
36 * 删除日期37 */
38 privateDate deleteDate;39
40 /**
41 * 删除标记42 */
43 private Boolean isDelete = false;44 }
2.4.3 TimesConfigApi.class
1 packagecom.springboot.quartz.api;2
3 importcom.springboot.quartz.dto.TimesConfigDto;4
5 importjava.util.List;6
7 /**
8 * @date 2018/6/39 */
10 public interfaceTimesConfigApi {11
12 /**
13 * 获取定时任务信息14 *@return
15 */
16 ListgetAllTimerInfo();17
18 /**
19 * 通过主键查询定时任务配置20 *@paramid21 *@return
22 */
23 TimesConfigDto findById(String id);24
25 /**
26 * 新增定时任务27 *@paramtimesConfigDto28 *@return
29 */
30 TimesConfigDto save(TimesConfigDto timesConfigDto);31
32 }
2.5 springboot-quartz-service 模块结构
2.5.1 pom.xml
1 <?xml version="1.0" encoding="UTF-8"?>
2
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
5
6 springboot-quartz
7 com.springboot.quartz
8 1.0-SNAPSHOT
9
10 4.0.0
11
12 springboot-quartz-service
13
14
15
16
17 org.springframework.boot
18 spring-boot-starter
19
20
21 ma.glasnost.orika
22 orika-core
23 1.5.2
24
25
26 mysql
27 mysql-connector-java
28
29
30
31 org.quartz-scheduler
32 quartz
33 2.2.1
34
35
36 org.springframework
37 spring-context-support
38
39
40
41
42 com.springboot.quartz
43 springboot-quartz-model
44 1.0-SNAPSHOT
45
46
47 com.springboot.quartz
48 springboot-quartz-api
49 1.0-SNAPSHOT
50
51
52
53
2.5.2 TimesConfigService.class
1 packagecom.springboot.quartz.service;2
3 importcom.springboot.quartz.dto.TimesConfigDto;4
5 importjava.util.List;6
7 /**
8 * @date 2018/6/39 */
10 public interfaceTimesConfigService {11
12 /**
13 * 获取全部未删除的配置14 *15 *@return
16 */
17 ListgetAll();18
19 /**
20 * 通过主键查询定时任务配置21 */
22 TimesConfigDto findByIdAndIsDelete(String id);23
24 /**
25 * 新增定时任务26 *@paramtimesConfigDto27 *@return
28 */
29 TimesConfigDto save(TimesConfigDto timesConfigDto);30
31 }
2.5.3 TimesConfigServiceImpl.class
1 packagecom.springboot.quartz.service.impl;2
3 importcom.springboot.quartz.dto.TimesConfigDto;4 importcom.springboot.quartz.model.TimesConfig;5 importcom.springboot.quartz.repository.TimesConfigRepository;6 importcom.springboot.quartz.service.TimesConfigService;7 importma.glasnost.orika.MapperFacade;8 importorg.springframework.beans.factory.annotation.Autowired;9 importorg.springframework.stereotype.Service;10
11 importjava.util.List;12
13 /**
14 * @date 2018/6/315 */
16 @Service17 public class TimesConfigServiceImpl implementsTimesConfigService {18
19 @Autowired20 TimesConfigRepository timesConfigRepository;21
22 @Autowired23 MapperFacade mapperFacade;24
25 /**
26 * 获取全部未删除的配置27 *28 *@return
29 */
30 @Override31 public ListgetAll() {32 List timesConfigs = timesConfigRepository.findByIsDelete(false);33 return mapperFacade.mapAsList(timesConfigs, TimesConfigDto.class);34 }35
36 /**
37 * 通过主键查询定时任务配置38 *@paramid39 *@return
40 */
41 @Override42 publicTimesConfigDto findByIdAndIsDelete(String id) {43 TimesConfig timesConfig = timesConfigRepository.findByIdAndIsDelete(id,false);44 return mapperFacade.map(timesConfig,TimesConfigDto.class);45 }46
47 /**
48 * 新增定时任务49 *@paramtimesConfigDto50 *@return
51 */
52 @Override53 publicTimesConfigDto save(TimesConfigDto timesConfigDto) {54 TimesConfig timesConfig = mapperFacade.map(timesConfigDto,TimesConfig.class);55 TimesConfig save =timesConfigRepository.save(timesConfig);56 return mapperFacade.map(save,TimesConfigDto.class);57 }58 }
2.5.4 TimesConfigApiImpl.class
1 packagecom.springboot.quartz.apiimpl;2
3 importcom.springboot.quartz.api.TimesConfigApi;4 importcom.springboot.quartz.dto.TimesConfigDto;5 importcom.springboot.quartz.service.TimesConfigService;6 importorg.springframework.beans.factory.annotation.Autowired;7 importorg.springframework.stereotype.Service;8
9 importjava.util.List;10
11 /**
12 * @date 2018/6/313 */
14 @Service15 public class TimesConfigApiImpl implementsTimesConfigApi {16
17 @Autowired18 TimesConfigService timesConfigService;19
20 /**
21 * 获取定时任务信息22 *@return
23 */
24 @Override25 public ListgetAllTimerInfo() {26 returntimesConfigService.getAll();27 }28
29 /**
30 * 通过主键查询定时任务配置31 *@paramid32 *@return
33 */
34 @Override35 publicTimesConfigDto findById(String id) {36 returntimesConfigService.findByIdAndIsDelete(id);37 }38
39 @Override40 publicTimesConfigDto save(TimesConfigDto timesConfigDto) {41 returntimesConfigService.save(timesConfigDto);42 }43 }
2.5.5 OrikaConfig.class
1 packagecom.springboot.quartz.config;2
3 importma.glasnost.orika.MapperFacade;4 importma.glasnost.orika.MapperFactory;5 importma.glasnost.orika.impl.DefaultMapperFactory;6 importma.glasnost.orika.metadata.ClassMapBuilder;7 importorg.springframework.context.annotation.Bean;8 importorg.springframework.context.annotation.Configuration;9
10 importjava.util.LinkedList;11 importjava.util.List;12
13
14 @Configuration15 public classOrikaConfig {16
17 @Bean18 MapperFactory mapperFactory() {19 MapperFactory mapperFactory = newDefaultMapperFactory.Builder().build();20 List builders = new LinkedList<>();21
22 for(ClassMapBuilder builder : builders) {23 builder.byDefault().register();24 }25 returnmapperFactory;26 }27
28 @Bean29 MapperFacade mapperFacade() {30 MapperFacade mapper =mapperFactory().getMapperFacade();31 returnmapper;32 }33
34
35 }
2.5.6 QuartzConfigration.class
1 packagecom.springboot.quartz.config;2
3 importcom.springboot.quartz.job.ScheduleTask;4 importorg.quartz.Trigger;5 importorg.springframework.context.annotation.Bean;6 importorg.springframework.context.annotation.Configuration;7 importorg.springframework.scheduling.quartz.CronTriggerFactoryBean;8 importorg.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean;9 importorg.springframework.scheduling.quartz.SchedulerFactoryBean;10
11 /**
12 * Quartz配置类13 */
14 @Configuration15 public classQuartzConfigration {16 /**
17 * 配置定时任务18 *19 *@paramtask20 *@return
21 */
22 @Bean(name = "jobDetail")23 public MethodInvokingJobDetailFactoryBean detailFactoryBean(ScheduleTask task) {//ScheduleTask为需要执行的任务
24 MethodInvokingJobDetailFactoryBean jobDetail = newMethodInvokingJobDetailFactoryBean();25
26 /**
27 * 是否并发执行28 * 例如每5s执行一次任务,但是当前任务还没有执行完,就已经过了5s了,29 * 如果此处为true,则下一个任务会执行,如果此处为false,则下一个任务会等待上一个任务执行完后,再开始执行30 */
31 jobDetail.setConcurrent(false);32
33 jobDetail.setName("srd-chhliu");//设置任务的名字
34 jobDetail.setGroup("srd");//设置任务的分组,这些属性都可以存储在数据库中,在多任务的时候使用
35
36 /**
37 * 为需要执行的实体类对应的对象38 */
39 jobDetail.setTargetObject(task);40
41 /**
42 * sayHello为需要执行的方法43 * 通过这几个配置,告诉JobDetailFactoryBean我们需要执行定时执行ScheduleTask类中的sayHello方法44 */
45 jobDetail.setTargetMethod("sayHello");46 returnjobDetail;47 }48
49 /**
50 * 配置定时任务的触发器,也就是什么时候触发执行定时任务51 *52 *@paramjobDetail53 *@return
54 */
55 @Bean(name = "jobTrigger")56 publicCronTriggerFactoryBean cronJobTrigger(MethodInvokingJobDetailFactoryBean jobDetail) {57 CronTriggerFactoryBean tigger = newCronTriggerFactoryBean();58 tigger.setJobDetail(jobDetail.getObject());59 tigger.setCronExpression("0 30 20 * * ?");//初始时的cron表达式
60 tigger.setName("srd-chhliu");//trigger的name
61 returntigger;62
63 }64
65 /**
66 * 定义quartz调度工厂67 *68 *@paramcronJobTrigger69 *@return
70 */
71 @Bean(name = "scheduler")72 publicSchedulerFactoryBean schedulerFactory(Trigger cronJobTrigger) {73 SchedulerFactoryBean bean = newSchedulerFactoryBean();74 //用于quartz集群,QuartzScheduler 启动时更新己存在的Job
75 bean.setOverwriteExistingJobs(true);76 //延时启动,应用启动1秒后
77 bean.setStartupDelay(1);78 //注册触发器
79 bean.setTriggers(cronJobTrigger);80 returnbean;81 }82 }
2.5.7 ScheduleRefreshDatabase.class
1 packagecom.springboot.quartz.config;2
3 importcom.springboot.quartz.api.TimesConfigApi;4 importcom.springboot.quartz.dto.TimesConfigDto;5 import org.quartz.*;6 importorg.springframework.beans.factory.annotation.Autowired;7 importorg.springframework.context.annotation.Configuration;8 importorg.springframework.scheduling.annotation.EnableScheduling;9 importorg.springframework.scheduling.annotation.Scheduled;10 importorg.springframework.stereotype.Component;11
12 importjavax.annotation.Resource;13
14 /**
15 * 定时查库,并更新任务16 */
17 @Configuration18 @EnableScheduling19 @Component20 public classScheduleRefreshDatabase {21
22 @Autowired23 privateTimesConfigApi timesConfigApi;24
25 @Resource(name = "jobDetail")26 privateJobDetail jobDetail;27
28 @Resource(name = "jobTrigger")29 privateCronTrigger cronTrigger;30
31 @Resource(name = "scheduler")32 privateScheduler scheduler;33
34 @Scheduled(fixedRate = 5000) //每隔5s查库,并根据查询结果决定是否重新设置定时任务
35 public void scheduleUpdateCronTrigger() throwsSchedulerException {36 CronTrigger trigger =(CronTrigger) scheduler.getTrigger(cronTrigger.getKey());37 String currentCron = trigger.getCronExpression();//当前Trigger使用的38 //String searchCron = repository.findOne("1").getCron();//从数据库查询出来的
39 TimesConfigDto timesConfigDto = timesConfigApi.findById("1");40 String searchCron =timesConfigDto.getCron();41 //System.out.println(currentCron);42 //System.out.println(searchCron);
43 if(currentCron.equals(searchCron)) {44 //如果当前使用的cron表达式和从数据库中查询出来的cron表达式一致,则不刷新任务
45 } else{46 //表达式调度构建器
47 CronScheduleBuilder scheduleBuilder =CronScheduleBuilder.cronSchedule(searchCron);48 //按新的cronExpression表达式重新构建trigger
49 trigger =(CronTrigger) scheduler.getTrigger(cronTrigger.getKey());50 trigger =trigger.getTriggerBuilder().withIdentity(cronTrigger.getKey())51 .withSchedule(scheduleBuilder).build();52 //按新的trigger重新设置job执行
53 scheduler.rescheduleJob(cronTrigger.getKey(), trigger);54 currentCron =searchCron;55 }56 }57 }
2.5.8 ScheduleTask.class
1 packagecom.springboot.quartz.job;2
3 importcom.springboot.quartz.api.TimesConfigApi;4 importcom.springboot.quartz.dto.TimesConfigDto;5 importorg.slf4j.Logger;6 importorg.slf4j.LoggerFactory;7 importorg.springframework.beans.factory.annotation.Autowired;8 importorg.springframework.context.annotation.Configuration;9 importorg.springframework.scheduling.annotation.EnableScheduling;10 importorg.springframework.stereotype.Component;11
12 importjava.util.List;13
14 /**
15 * 任务类16 */
17 @Configuration18 @Component //此注解必加
19 @EnableScheduling //此注解必加
20 public classScheduleTask {21 private static final Logger LOGGER = LoggerFactory.getLogger(ScheduleTask.class);22
23 @Autowired24 privateTimesConfigApi timesConfigApi;25
26 public voidsayHello() {27 /*TimesConfigDto timesConfigDto = new TimesConfigDto();28 timesConfigDto.setCron("0/5 * * * * ?");29 timesConfigApi.save(timesConfigDto);30 System.out.println("添加成功");*/
31 List allTimerInfo =timesConfigApi.getAllTimerInfo();32 System.out.println("执行成功");33 LOGGER.info("Hello world, i'm the king of the world!!!");34 }35 }
2.5.9 application.properties
1 # 服务器端口号2 server.port=79033 #配置数据源4 spring.datasource.driver-class-name=com.mysql.jdbc.Driver5 spring.datasource.url=jdbc:mysql://localhost:3306/time16 spring.datasource.username=root7 spring.datasource.password=root8 spring.jpa.hibernate.ddl-auto=update9 spring.jpa.show-sql=false10
11 #在控制台输出彩色日志12 spring.output.ansi.enabled=always
2.5.10 SpringbootQuartzApplication.class
1 packagecom.springboot.quartz;2
3 importorg.springframework.boot.SpringApplication;4 importorg.springframework.boot.autoconfigure.SpringBootApplication;5
6 /**
7 * @date 2018/6/28 */
9 @SpringBootApplication10 public classSpringbootQuartzApplication {11 public static voidmain(String[] args) {12 SpringApplication.run(SpringbootQuartzApplication.class, args);13 }14 }
2.6 启动 SpringbootQuartzApplication.class
3. springboot-timedTask springboot自带的定时任务
3.1 pom.xml
1 <?xml version="1.0" encoding="UTF-8"?>
2
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
5 4.0.0
6
7 com.timetask
8 springboot-timedTask
9 1.0-SNAPSHOT
10
11
12
13 org.springframework.boot
14 spring-boot-starter-parent
15 1.4.1.RELEASE
16
17
18
19
20
21 org.springframework.boot
22 spring-boot-starter-web
23
24
25
26
27
28
29 org.springframework.boot
30 spring-boot-maven-plugin
31
32
33
34 repackage
35
36
37
38
39 true
40
41
42
43
44
3.2 PrintTask.class
1 packagecom.timetask.test;2
3 importorg.springframework.scheduling.annotation.Scheduled;4 importorg.springframework.stereotype.Component;5 importjava.text.SimpleDateFormat;6 importjava.util.Date;7
8 /**
9 * @date 2018/6/210 */
11 @Component12 public classPrintTask {13
14 //每分钟启动15 //@Scheduled(cron = "0 0/1 * * * ?")
16 @Scheduled(cron = "0/5 * * * * ? ") //间隔5秒执行
17 public voidcron(){18 System.out.println("执行测试时间:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(newDate()));19 }20 }
3.3 application.properties
1 server.port=8083
3.4 SpringBootTimeTaskApplication.class
1 packagecom.timetask;2
3 importorg.springframework.boot.SpringApplication;4 importorg.springframework.boot.autoconfigure.SpringBootApplication;5 importorg.springframework.scheduling.annotation.EnableScheduling;6
7 @SpringBootApplication8 @EnableScheduling //开启定时任务
9 public classSpringBootTimeTaskApplication {10
11 public static voidmain(String[] args) {12 SpringApplication.run(SpringBootTimeTaskApplication.class, args);13 }14
15 }
3.5 执行SpringBootTimeTaskApplication.class