欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

springboot 集成Quartz 实现定时任务

程序员文章站 2022-05-07 16:45:32
...

           本章我们使用Quartz在java project的项目中进行定时任务的实现,首先我们需要在pom文件引入 quartz jar 包,

          

           <dependency>

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

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

           </dependency>

 

           接下来我们编写具体的执行任务类,具体的执行需要继承QuartzJobBean 类 或者job接口都可以,我们这里是继承QuartzJobBean 类    ,如下:

     

 

import org.quartz.JobExecutionContext;

import org.quartz.JobExecutionException;

import org.springframework.scheduling.quartz.QuartzJobBean;

 

public class HelloworldJob extends QuartzJobBean  {

 

@Override

public void executeInternal(JobExecutionContext context) throws JobExecutionException {

// TODO Auto-generated method stub

System.out.println("Hello world!:" + context.getJobDetail().getKey());

}

 

}

 

        接下来编写任务的启动类,需要在类上加@Configuration注解,以便被扫描到,在方法上增加注解@Bean,注入倒容器中,如下:

 

 

import org.quartz.CronScheduleBuilder;

import org.quartz.JobBuilder;

import org.quartz.JobDetail;

import org.quartz.Trigger;

import org.quartz.TriggerBuilder;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

@Configuration

public class QuartzDemo {

@Bean

    public JobDetail myJobDetail(){

       JobDetail jobDetail = JobBuilder.newJob(HelloworldJob.class)

            .withIdentity("myJob1","myJobGroup1")//定义Job类为HelloworldJob类,这是真正的执行逻辑所在

            .usingJobData("job_param","job_param1")//给任务execute传递参数

            .storeDurably()

                .build();

        return jobDetail;

    }

    @Bean

    public Trigger myTrigger(){

        Trigger trigger = TriggerBuilder.newTrigger()

                .forJob(myJobDetail())

                .withIdentity("myTrigger1","myTriggerGroup1")

                .usingJobData("job_trigger_param","job_trigger_param1")

                .startNow()

                //.withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(5).repeatForever())

                .withSchedule(CronScheduleBuilder.cronSchedule("0/5 * * * * ? 2019"))

                .build();

        return trigger;

    }

 

}

 

 

下面启动项目就能看到任务打印信息了:

Hello world  Quartz !:myJobGroup1.myJob1

Hello world  Quartz !:myJobGroup1.myJob1

Hello world  Quartz !:myJobGroup1.myJob1

Hello world  Quartz !:myJobGroup1.myJob1

Hello world  Quartz !:myJobGroup1.myJob1

Hello world  Quartz !:myJobGroup1.myJob1

Hello world  Quartz !:myJobGroup1.myJob1

Hello world  Quartz !:myJobGroup1.myJob1