SpringBoot2.x整合quartz实现多任务定时执行
一、pom文件中导入相关依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-quartz</artifactId> </dependency>
二、分别编写任务代码类
/** * 任务一 */ public class MyQuartzJob extends QuartzJobBean { @Override protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException { System.out.println("talk is cheap."); } }
/** * 任务二 */ public class MyQuartzJob1 extends QuartzJobBean { @Override protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException { System.out.println("show me the code"); } }
三、分别编写相关的scheduler类(也可以写在一个类里)
/** * Scheduler来调度Trigger和JobDetil * JobDetail来实例化Job类并可以传值 */ @Configuration public class MyScheduler { @Bean(name = "JobDetail") public JobDetail simpleJobDetail(){ JobDetail jobDetail = JobBuilder.newJob(MyQuartzJob.class).withIdentity("eclipse") .usingJobData("key","value").storeDurably().build(); return jobDetail; } @Bean(name = "trigger") public Trigger simpleJobTrigger(){ SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(4).repeatForever(); return TriggerBuilder.newTrigger().forJob(simpleJobDetail()) .withIdentity("sampleTrigger").withSchedule(scheduleBuilder).build(); } }
@Configuration public class MyScheduler1 { @Bean(name = "JobDetail1") public JobDetail simpleJobDetail1(){ JobDetail jobDetail = JobBuilder.newJob(MyQuartzJob1.class).withIdentity("eclipse1") .usingJobData("key","value").storeDurably().build(); return jobDetail; } @Bean(name = "trigger1") public Trigger simpleJobTrigger1(){ SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(6).repeatForever(); return TriggerBuilder.newTrigger().forJob(simpleJobDetail1()) .withIdentity("sampleTrigger1").withSchedule(scheduleBuilder).build(); } }
四、启动springboot即可查看任务执行情况
具体的执行时间可以自己设置:这里分别是4秒和6秒: