Spring Boot系列之quartz

2025-11-14 11:14:33

1、新建项目

项目核心分3部分,pom依赖spring-boot-starter-quartz,job类MyJob,MyJobApplication

Spring Boot系列之quartz

2、引入quartz依赖。

在pom.xml中引入jar依赖

<dependency>

  <groupId>org.springframework.boot</groupId>

  <artifactId>spring-boot-starter-quartz</artifactId>

</dependency>

Spring Boot系列之quartz

3、定义job类

该类继承QuartzJobBean类,并实现executeInternal方法。此方法中可书写具体的业务逻辑处理。

public class MyJob extends QuartzJobBean {

   private final Logger LOG = LoggerFactory.getLogger(MyJob.class);

   private String name;

   public void setName(String name) {

       this.name = name;

   }

   @Override

   protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {

       LOG.info("hi {}",this.name);

   }

}

Spring Boot系列之quartz

4、定义jobDetail和Trigger,并运行程序

定义JobDetail的job类为MyJob,id为myjob1,name的值为myname1;

定义调度Schedule每10s执行一次;定义Trigger,按照schedule机制来调度,并执行JobDetail相关任务。

@SpringBootApplication

public class MyJobApplication {

  @Bean

  public JobDetail jobDetail() {

     return JobBuilder.newJob(MyJob.class)            .withIdentity("myjob1").usingJobData("name","myname1")            .storeDurably().build();

  }

  @Bean

  public Trigger trigger() {

     SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder            .simpleSchedule().withIntervalInSeconds(10).repeatForever();

     return TriggerBuilder.newTrigger().forJob(jobDetail())            .withIdentity("mytrigger1").withSchedule(scheduleBuilder).build();

  }

  public static void main(String[] args) {

     SpringApplication.run(MyJobApplication.class, args);

  }

}

Spring Boot系列之quartz

5、测试结果1

从结果时间可以看出,每隔10s输出一次日志。可见quartz已经完美的调度了job任务

Spring Boot系列之quartz

6、测试结果2

修改调度设置,每分钟执行一次。运行结果见图

SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder      .simpleSchedule().withIntervalInMinutes(1).repeatForever();

Spring Boot系列之quartz

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢