SpringBoot(二)集成 Quartz:2.5.4

news/2024/7/10 5:34:55 标签: spring boot, 后端, java, Quartz

Quartz是一个广泛使用的开源任务调度框架,用于在Java应用程序中执行定时任务和周期性任务。它提供了强大的调度功能,允许您计划、管理和执行各种任务,从简单的任务到复杂的任务。

以下是Quartz的一些关键特点和功能:

  • 灵活的调度器:Quartz提供了一个高度可配置的调度器,允许您根据不同的时间表执行任务,包括固定的时间、每日、每周、每月、每秒等。您可以设置任务执行的时间和频率。
  • 多任务支持:Quartz支持同时管理和执行多个任务。您可以定义多个作业和触发器,并将它们添加到调度器中。
  • 集群和分布式调度:Quartz支持集群模式,可以在多台机器上协调任务的执行。这使得Quartz非常适合大规模和分布式应用,以确保任务的高可用性和负载均衡。
  • 持久化:Quartz可以将任务和调度信息持久化到数据库中,以便在应用程序重启时不会丢失任务信息。这对于可靠性和数据保持非常重要。
  • 错过任务处理:Quartz可以配置在任务错过执行时如何处理,例如,是否立即执行、延迟执行或丢弃任务。
  • 监听器:Quartz提供了各种监听器,可以用来监视任务的执行,以及在任务执行前后执行自定义操作。
  • 多种作业类型:Quartz支持不同类型的作业,包括无状态作业(Stateless Job)和有状态作业(Stateful
    Job)。这允许您选择最适合您需求的作业类型。
  • 插件机制:Quartz具有灵活的插件机制,可以扩展其功能。您可以创建自定义插件,以满足特定需求。
  • 丰富的API:Quartz提供了丰富的Java API,使任务调度的配置和管理非常方便。

依赖

       <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-quartz</artifactId>
            <version>2.5.4</version>
        </dependency>

配置

spring.quartz.job-store-type=jdbc
# The first boot uses ALWAYS
spring.quartz.jdbc.initialize-schema=never
spring.quartz.auto-startup=true
spring.quartz.startup-delay=5s
spring.quartz.overwrite-existing-jobs=true
spring.quartz.properties.org.quartz.scheduler.instanceName=ClusterQuartz
spring.quartz.properties.org.quartz.scheduler.instanceId=AUTO
spring.quartz.properties.org.quartz.jobStore.class=org.springframework.scheduling.quartz.LocalDataSourceJobStore
spring.quartz.properties.org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.PostgreSQLDelegate
spring.quartz.properties.org.quartz.jobStore.tablePrefix=QRTZ_
spring.quartz.properties.org.quartz.jobStore.isClustered=true
spring.quartz.properties.org.quartz.jobStore.acquireTriggersWithinLock=true
spring.quartz.properties.org.quartz.jobStore.misfireThreshold=12000
spring.quartz.properties.org.quartz.jobStore.clusterCheckinInterval=5000
spring.quartz.properties.org.quartz.threadPool.class=org.quartz.simpl.SimpleThreadPool
spring.quartz.properties.org.quartz.threadPool.threadCount=1
spring.quartz.properties.org.quartz.threadPool.threadPriority=5
spring.quartz.properties.org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread=true


job


import cn.hutool.extra.spring.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.PersistJobDataAfterExecution;
import org.springframework.stereotype.Component;

/**
 * @author Wang
 */
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
@Slf4j
@Component
public class DealerJob implements Job {

    @Override
    public void execute(JobExecutionContext context) {
        log.info("start Quartz job name: {}", context.getJobDetail().getKey().getName());
        DealerImportFacade dealerImportFacade = SpringUtil.getBean(DealerImportFacade.class);

        log.info(" start import US dealer data ");
        RequestContext.current().set(RequestContextCons.REGION, DataSourceEnum.US.toString().toLowerCase());
        try {
//            dealerImportFacade.importUsDealerData();
            log.info(" end import US dealer data ");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
}

controller


import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * @author Wang
 */
@RequiredArgsConstructor
@Slf4j
@RestController
@RequestMapping("/schedule/job")
public class ScheduleJobController {

    final ScheduleJobService scheduleJobService;
    final QuartzHelper quartzHelper;

    @PostMapping
    public AjaxRespData<ScheduleJobVO> addJob(@Valid @RequestBody AddScheduleJobDTO scheduleJobDTO) {
        ScheduleJobEntity scheduleJobEntity = BeanConvertUtils.convert(scheduleJobDTO, ScheduleJobEntity.class);
        scheduleJobEntity.init();
        scheduleJobEntity.setStatus(EnumScheduleJobStatus.RUN);
        ScheduleJobData data = scheduleJobService.save(scheduleJobEntity);
        quartzHelper.scheduleJob(data);
        return AjaxRespData.success(BeanConvertUtils.convert(data, ScheduleJobVO.class));
    }

    @DeleteMapping("/{jobId}")
    public AjaxRespData<Void> removeJob(@PathVariable("jobId") String jobId) {
        ScheduleJobEntity scheduleJobEntity = scheduleJobService.checkExist(jobId, EnumError.E30001);
        scheduleJobService.remove(jobId);
        quartzHelper.remove(scheduleJobEntity);
        return AjaxRespData.success();
    }

    @PutMapping("/{jobId}")
    public AjaxRespData<ScheduleJobVO> updateJob(@PathVariable String jobId, @Valid @RequestBody AddScheduleJobDTO scheduleJobDTO) {
        ScheduleJobEntity scheduleJobEntity = BeanConvertUtils.convert(scheduleJobDTO, ScheduleJobEntity.class);
        scheduleJobEntity.setId(jobId);
        ScheduleJobData data = scheduleJobService.update(scheduleJobEntity);
        quartzHelper.scheduleJob(data);
        return AjaxRespData.success(BeanConvertUtils.convert(data, ScheduleJobVO.class));
    }

    @GetMapping("/{jobId}")
    public AjaxRespData<ScheduleJobVO> getJob(@PathVariable("jobId") String jobId) {
        ScheduleJobEntity scheduleJobEntity = scheduleJobService.checkExist(jobId, EnumError.E30001);
        return AjaxRespData.success(BeanConvertUtils.convert(scheduleJobEntity, ScheduleJobVO.class));
    }


    @PutMapping("/operate")
    public void operateJob(@Valid @RequestBody AddScheduleJobDTO scheduleJobDTO) {
        ScheduleJobEntity scheduleJobEntity = scheduleJobService.checkExist(scheduleJobDTO.getId(), EnumError.E30001);
        scheduleJobEntity.setStatus(scheduleJobDTO.getStatus());
        scheduleJobService.update(scheduleJobEntity);
        quartzHelper.operateJob(scheduleJobDTO.getStatus(), scheduleJobEntity);
    }

}

service


import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author Wang
 */
@RequiredArgsConstructor
@Slf4j
@Service
public class ScheduleJobService extends BaseService<ScheduleJobEntity, ScheduleJobData> {

    final ScheduleJobRepository scheduleJobRepository;
    final QuartzHelper quartzHelper;

    @PostConstruct
    public void init(){
        log.info("init schedule job...");
        List<ScheduleJobEntity> jobs = this.getRepository().findAll();
        for (ScheduleJobEntity job : jobs) {
            quartzHelper.scheduleJob(job);
            quartzHelper.operateJob(EnumScheduleJobStatus.PAUSE, job);
            if (job.getStatus().equals(EnumScheduleJobStatus.RUN)) {
                quartzHelper.operateJob(EnumScheduleJobStatus.RUN, job);
            }
        }
        log.info("init schedule job completed...");
    }

    @Override
    public BaseRepository<ScheduleJobEntity> getRepository() {
        return scheduleJobRepository;
    }


}

helper


import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.stereotype.Component;

import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Objects;

/**
 * @author Wang
 */
@RequiredArgsConstructor
@Slf4j
@Component
public class QuartzHelper {

    final Scheduler scheduler;

    public void scheduleJob(ScheduleJobEntity jobInfo) {

        JobKey jobKey = JobKey.jobKey(jobInfo.getJobName(), jobInfo.getJobGroup());
        try {
            JobDetail jobDetail = scheduler.getJobDetail(jobKey);
            if (Objects.nonNull(jobDetail)){
                scheduler.deleteJob(jobKey);
            }
        } catch (SchedulerException e) {
            e.printStackTrace();
        }

        JobDetail jobDetail = JobBuilder.newJob(getJobClass(jobInfo.getType()))
                .withIdentity(jobKey)
                .build();

        Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity(jobInfo.getTriggerName(), jobInfo.getTriggerGroup()).startNow()
                .withSchedule(CronScheduleBuilder.cronSchedule(jobInfo.getCronExpression()))
                .build();

        try {
            scheduler.scheduleJob(jobDetail, trigger);
        } catch (SchedulerException e) {
            log.error(e.getMessage(), e);
        }
    }

    public void rescheduleJob(ScheduleJobEntity job) {

        TriggerKey triggerKey = new TriggerKey(job.getTriggerName(), job.getTriggerGroup());
        try {
            CronTrigger cronTrigger = (CronTrigger) scheduler.getTrigger(triggerKey);

            CronTrigger newCronTrigger = cronTrigger.getTriggerBuilder()
                    .withIdentity(triggerKey)
                    .withSchedule(CronScheduleBuilder.cronSchedule(job.getCronExpression()))
                    .build();

            scheduler.rescheduleJob(triggerKey, newCronTrigger);
        } catch (SchedulerException e) {
            throw new RuntimeException(e);
        }
    }

    public void remove(ScheduleJobEntity job) {
        TriggerKey triggerKey = new TriggerKey(job.getTriggerName(), job.getTriggerGroup());
        try {
            scheduler.pauseTrigger(triggerKey);
            scheduler.unscheduleJob(triggerKey);
            scheduler.deleteJob(JobKey.jobKey(job.getTriggerName(), job.getTriggerGroup()));
        } catch (SchedulerException e) {
            throw new RuntimeException(e);
        }
    }

    public void unscheduleJob(ScheduleJobEntity job) {

        TriggerKey triggerKey = new TriggerKey(job.getTriggerName(), job.getTriggerGroup());
        try {
            scheduler.unscheduleJob(triggerKey);
        } catch (SchedulerException e) {
            throw new RuntimeException(e);
        }
    }

    public void operateJob(EnumScheduleJobStatus status, ScheduleJobEntity job) {
        JobKey jobKey = JobKey.jobKey(job.getJobName(), job.getJobGroup());
        try {
            switch (status) {
                case RUN:
                    scheduler.resumeJob(jobKey);
                    break;
                case PAUSE:
                    scheduler.pauseJob(jobKey);
                    break;
                default:
                    throw new IllegalArgumentException();
            }
        } catch (SchedulerException e) {
            throw new RuntimeException(e);
        }
    }

    public String nextTime(ScheduleJobEntity job) {
        TriggerKey triggerKey = new TriggerKey(job.getTriggerName(), job.getTriggerGroup());
        try {
            Trigger trigger = scheduler.getTrigger(triggerKey);
            Date nextFireTime = trigger.getNextFireTime();
            return DateUtil.format(nextFireTime, DateTimeFormatter.ISO_DATE_TIME);
        } catch (SchedulerException e) {
            throw new RuntimeException(e);
        }
    }

    private Class<? extends Job> getJobClass(EnumScheduleJobType type) {
        Class<? extends Job> clazz;
        switch (type) {
            case DEALER_IMPORT:
                clazz = DealerJob.class;
                break;
//            case SECONDARY_INVITING_EXPIRE:
//                clazz = MockDeviceReportJob.class;
//                break;
            default:
                throw new IllegalArgumentException();
        }
        return clazz;
    }
}

最终效果

实例1,8281
在这里插入图片描述
实例2,8282
在这里插入图片描述

踩坑

定时任务执行间隔,最低设置一分钟


http://www.niftyadmin.cn/n/5109166.html

相关文章

C++ vector 的使用

CSDN的uu们&#xff0c;大家好。这里是C入门的第十七讲。 座右铭&#xff1a;前路坎坷&#xff0c;披荆斩棘&#xff0c;扶摇直上。 博客主页&#xff1a; 姬如祎 收录专栏&#xff1a;C专题 目录 1. 构造函数 1.1 vector(size_t n, const T& val T()) 1.2 vector…

安装node.js和vue-cli脚手架,实现vue项目和springboot项目前后端数据交互

1、安装node.js 太高版本的win7不支持 这里安装node-v12.16.2-x64.msi&#xff0c;指定安装位置后直接按下一步就可以。npm是node内置的工具 这里配置npm的镜像cnpm&#xff08;提高下载速度&#xff0c;以后用到npm的命令都可以用cnpm命令替换&#xff09;不指定cnpm版本使用…

边缘检测算法

边缘检测算法是在数字图像处理中常用的一种技术&#xff0c;用于检测图像中物体边缘的位置。以下是几种常见的边缘检测算法&#xff1a; Sobel算子&#xff1a;Sobel算子是一种基于梯度的算法&#xff0c;通过计算图像的水平和垂直方向的梯度值&#xff0c;并将其组合起来得到边…

软件项目管理【UML-组件图】

目录 一、组件图概念 二、组件图包含的元素 1.组件&#xff08;Component&#xff09;->构件 2.接口&#xff08;Interface&#xff09; 3.外部接口——端口 4.连接器&#xff08;Connector&#xff09;——连接件 4.关系 5.组件图表示方法 三、例子 一、组件图概念…

androidstudio调试下,闪退没有日志怎么解决 应用闪退日志

假如当一个安卓app闪退了&#xff0c;然后操作发现不是的必现的时候&#xff0c;你是怎么解决&#xff0c;提交Bug的&#xff0c;怎么确定最后是否解决的&#xff1f; 1.很多的人的回答是尽量的去回忆操作步骤&#xff0c;然后一直重现&#xff0c;并先提交一个条Bug,作为多个…

英伟达禁售?FlashAttention助力LLM推理速度提8倍

人工智能领域快速发展&#xff0c;美国拥有强大的AI芯片算力&#xff0c;国内大部分的高端AI芯片都是采购英伟达和AMD的。而为了阻止中国人工智能领域发展&#xff0c;美国频繁采取出口管制措施。10月17日&#xff0c;美国拜登突然宣布&#xff0c;升级芯片出口禁令。英伟达限制…

PeopleCode中Date函数的用法

语法 Date(date_num) 描述 The Date function takes a number in the form YYYYMMDD and returns a corresponding Date value. If the date is invalid, Date displays an error message. Date函数输入是一个形如“YYYYMMDD”的数字&#xff0c;返回一个相应的Date类型的值…

【微信小程序】后台数据交互于WX文件使用

目录 一、前期准备 1.1 数据库准备 1.2 后端数据获取接口编写 1.3 前端配置接口 1.4 封装微信的request请求 二、WXS文件的使用 2.1 WXS简介 2.2 WXS使用 三、后台数据交互完整代码 3.1 WXML 3.2 JS 3.3 WXSS 效果图 一、前期准备 1.1 数据库准备 创建数据库&…