SpringBoot 集成 Quartz 实现定时任务功能

相关概念

① Job:任务 (要做什么)
② Trigger:触发器 (什么时候做)
③ Scheduler: 任务调度器 (什么时候做什么事情)

功能效果图

SpringBoot 集成 Quartz 实现定时任务功能_第1张图片

具体实现

引入相关依赖

<!-- quartz autoJob-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-quartz</artifactId>
		</dependency>

第一种方式

import lombok.extern.slf4j.Slf4j;
import org.quartz.JobDetail;
import org.quartz.Trigger;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
import org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Configuration
public class QuartzConfig {

    //配置调度器
    @Bean
    public SchedulerFactoryBean schedulerFactory(Trigger helloTrigger, Trigger hello1Trigger) {
        SchedulerFactoryBean bean = new SchedulerFactoryBean();
        List<Trigger> triggerList = new ArrayList<>(); //存储配置文件配置对应的触发器

        triggerList.add(helloTrigger);
        triggerList.add(hello1Trigger);

        if (!triggerList.isEmpty()) {
            Trigger[] ts = new Trigger[triggerList.size()];
            for (int i = 0; i < triggerList.size(); i++) {
                ts[i] = triggerList.get(i);
            }
            bean.setTriggers(ts);
        } else {
            throw new RuntimeException("没有合适的触发器组合搭配");
        }

        return bean;
    }

    static class Hello {
        public void hello() {
            System.out.println("hello");
        }
    }

    static class Hello1 {
        public void hello() {
            System.out.println("hello1");
        }
    }

    @Bean("helloJob")
    public MethodInvokingJobDetailFactoryBean helloJob() {
        printInitLog("helloJob");
        Hello hello = new Hello();
        return publicJobOperation(hello, "hello");
    }  
    
    @Bean("hello1Job")
    public MethodInvokingJobDetailFactoryBean helloJob1() {
        printInitLog("helloJob1");
        Hello1 hello1 = new Hello1();
        return publicJobOperation(hello1, "hello");
    }
    

    @Bean
    public CronTriggerFactoryBean helloTrigger(JobDetail helloJob) {
        return newCronTrigger(helloJob);
    }

    @Bean
    public CronTriggerFactoryBean hello1Trigger(JobDetail hello1Job) {
        return newCronTrigger(hello1Job);
    }

    //配置触发器
    private CronTriggerFactoryBean newCronTrigger(JobDetail jobDetail) {
        CronTriggerFactoryBean bean = new CronTriggerFactoryBean();
        bean.setJobDetail(jobDetail);
        bean.setCronExpression("0/3 * * * * ?");
        return bean;
    }

    private String getDate() {
        return LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }

    private void printInitLog(String jobName) {
        log.info(jobName + "任务初始化名称: " + Thread.currentThread().getName() + ",时间: " + getDate());
    }

    // job的公共操作
    public MethodInvokingJobDetailFactoryBean publicJobOperation(Object o, String method) {
        MethodInvokingJobDetailFactoryBean bean = new MethodInvokingJobDetailFactoryBean();
        bean.setConcurrent(false); //同一job不允许并发操作
        bean.setTargetObject(o); //需要执行的实体类对象
        bean.setTargetMethod(method); //需要执行的实体类的方法
        return bean;
    }

}

第二种方式

Job

public class HelloJob {

    public void hello() {
        System.out.println("============== Hello ==============");
    }
}

ScheduleConfig

@Configuration
public class ScheduleConfigOne {

    public MethodInvokingJobDetailFactoryBean methodInvokingJobDetailFactoryBean(Object entity, String method) {
        MethodInvokingJobDetailFactoryBean bean = new MethodInvokingJobDetailFactoryBean();
        bean.setConcurrent(false); //同一Job不允许并发操作
        bean.setTargetObject(entity); //需要执行的实体类对象
        bean.setTargetMethod(method); //需要执行的实体类的方法
        return bean;
    }

    //配置定时任务
    @Bean
    public MethodInvokingJobDetailFactoryBean helloJob() {
        HelloJob helloJob = new HelloJob();
        return methodInvokingJobDetailFactoryBean(helloJob, "hello");
    }

    //配置触发器
    @Bean
    public CronTriggerFactoryBean helloTrigger(JobDetail helloJob) {
        CronTriggerFactoryBean bean = new CronTriggerFactoryBean();
        bean.setJobDetail(helloJob);
        bean.setCronExpression("0 0/1 * * * ?");
        return bean;
    }

    //配置调度器
    @Bean
    public SchedulerFactoryBean schedulerFactory(Trigger helloTrigger) {
        SchedulerFactoryBean bean = new SchedulerFactoryBean();
        bean.setTriggers(helloTrigger);
        return bean;
    }

}

第三种方式

HelloJob

@Component
public class HelloJob extends QuartzJobBean {

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        System.out.println("============== Hello ==============");
    }
}

ScheduleConfig

@Configuration
public class ScheduleConfig {

    @Bean
    public MethodInvokingJobDetailFactoryBean methodInvokingJobDetailFactoryBean() {
        MethodInvokingJobDetailFactoryBean bean = new MethodInvokingJobDetailFactoryBean();
        bean.setConcurrent(false); //同一job不允许并发运行
        return bean;
    }

    @Bean
    public JobDetail jobDetail(){
        return JobBuilder.newJob(HelloJob.class)
                .withIdentity("HelloJob")
                .storeDurably()
                .build();
    }

    @Bean
    public Trigger trigger(){
        // 每5秒执行一次
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule("0/5 * * * * ? ");
        return TriggerBuilder.newTrigger()
                .forJob(jobDetail())
                .withIdentity("HelloTrigger")
                .withSchedule(cronScheduleBuilder)
                .build();
    }

}

你可能感兴趣的:(java,spring,boot,java,Quartz)