SpringBoot整合Quartz

72 阅读2分钟

Quartz

定时任务框架

github文档:

quartz/docs/index.adoc at main · quartz-scheduler/quartz (github.com)

cron:任务调度规则

quartz/docs/tutorials/crontrigger.md at main · quartz-scheduler/quartz (github.com)

依赖

<!-- 引入 Quartz 定时任务 依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-quartz</artifactId>
        </dependency>

Job实现

Job是任务接口,也可以继承QuartzJobBean抽象类,该类起到的是传换器的作用,下面的即是实现该代码的接口

实现代码

package com.example.portablefortheelderlybackground.config.Quartz.job;

import com.example.portablefortheelderlybackground.sevice.lookHistoryService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author 86187
 * @description: 定时清理用户观看记录
 * @date: 2023/10/19 23:12
 */
@Component
@Slf4j
public class ClearScienceHistoryByUserAndTimeJob extends QuartzJobBean {
    private final lookHistoryService lookHistoryService;

    public ClearScienceHistoryByUserAndTimeJob(lookHistoryService lookHistoryService) {
        this.lookHistoryService = lookHistoryService;
    }

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        log.info("{}开始执行删除历史记录任务", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        //执行定时任务
        Boolean isSUCCESS = lookHistoryService.deleteScienceByStatus().data;
        log.info("{}执行删除定历史记录时任务{}", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")), isSUCCESS ? "成功" : "失败");
    }
}

job和QuartzJobBean

QuartzJobBean
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package org.springframework.scheduling.quartz;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.SchedulerException;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.PropertyAccessorFactory;

public abstract class QuartzJobBean implements Job {
    public QuartzJobBean() {
    }

    public final void execute(JobExecutionContext context) throws JobExecutionException {
        try {
            BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);
            MutablePropertyValues pvs = new MutablePropertyValues();
            pvs.addPropertyValues(context.getScheduler().getContext());
            pvs.addPropertyValues(context.getMergedJobDataMap());
            bw.setPropertyValues(pvs, true);
        } catch (SchedulerException var4) {
            throw new JobExecutionException(var4);
        }

        this.executeInternal(context);//外部调用Job的接口方法,这里继而调用该类地抽象方法
    }

    protected abstract void executeInternal(JobExecutionContext context) throws JobExecutionException;
}

Job
package org.quartz;

public interface Job {

    void execute(JobExecutionContext context)
        throws JobExecutionException;

}

配置

交由spring管理,内部管理注册Quartz的任务bean和触发器bean,

如果要开启多个定时任务,可以给bean起不同的名称,继而实现多任务开启

package com.example.portablefortheelderlybackground.config.Quartz;

import com.example.portablefortheelderlybackground.config.Quartz.job.ClearScienceHistoryByUserAndTimeJob;
import org.quartz.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class QuartzConfig {
    @Bean()
    public JobDetail jobDetail() {
        return JobBuilder.newJob(ClearScienceHistoryByUserAndTimeJob.class)
                .withDescription("")// 任务描述
                .withIdentity("测试任务")// 任务名称
                .storeDurably()// 每次任务执行后存储
                .build();// 构建
    }

    @Bean
    public Trigger trigger() {
        //创建触发器
        return TriggerBuilder.newTrigger()
                // 绑定工作任务
                .forJob(jobDetail())
                // 每隔 5 秒执行一次 job
                .withIdentity("ClearHistory")
                //.withSchedule(SimpleScheduleBuilder.repeatSecondlyForever(5))
                .withSchedule(CronScheduleBuilder.cronSchedule("0 0 0 * * ?"))
                .build();
    }
}