bootstrap的quartz定时任务简单使用
(1)导入quartz
<!--quartz定时调度依赖--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-quartz</artifactId> </dependency>
(2)设置定时任务的执行
package com.example.demo.config; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.springframework.scheduling.quartz.QuartzJobBean; import java.text.SimpleDateFormat; import java.util.Date; //设置定制任务的执行 class QuartzJob1 extends QuartzJobBean { @Override protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException { SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); System.out.println("QuartzJob1----" + sdf.format(new Date())); } }
(3)设置配置文件
package com.example.demo.config; import org.quartz.*; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class QuartzConfig { @Bean public JobDetail jobDetail1(){ return JobBuilder.newJob(QuartzJob1.class).storeDurably().build(); } @Bean public Trigger trigger1(){ SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule() .withIntervalInSeconds(1) //每一秒执行一次 .repeatForever(); //永久重复,一直执行下去 return TriggerBuilder.newTrigger() .forJob(jobDetail1()) .withSchedule(scheduleBuilder) .build(); } }
也可以使用内部类
@Bean public JobDetail jobDetail2(){ QuartzJobBean quartzJob2 = new QuartzJobBean() { @Override protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException { SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); System.out.println("内部类quartzJob2----" + sdf.format(new Date())); } }; return JobBuilder.newJob(quartzJob2.getClass()).storeDurably().build(); } @Bean public Trigger trigger2(){ //JobDetail的bean注入不能省略 //JobDetail jobDetail3 = JobBuilder.newJob(QuartzJob2.class).storeDurably().build(); SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule() .withIntervalInSeconds(2) //每2秒执行一次 .repeatForever(); //永久重复,一直执行下去 return TriggerBuilder.newTrigger() .forJob(jobDetail2()) .withSchedule(scheduleBuilder).build(); }
打印数据:
QuartzJob1----2020-11-01 14:18:30 QuartzJob1----2020-11-01 14:18:31 QuartzJob1----2020-11-01 14:18:32
地址:https://www.cnblogs.com/imyanger/p/11828301.html