springboot 整合quartz定时任务

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

文章目录


前言

提示:这里可以添加本文要记录的大概内容:


提示:以下是本篇文章正文内容,下面案例可供参考

一、pom的配置

java 复制代码
 <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
            <version>2.3.2</version>
        </dependency>

        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.3</version>
        </dependency>

1.加注解

c 复制代码
@EnableScheduling
public class BusinessApplication {
    public static void main(String[] args) {
        SpringApplication.run(BusinessApplication.class, args);
        log.info("*********启动成功************");
    }

}

二、使用方法

1.工程图

2.创建工具类

java 复制代码
package com.juyuan.api.scheduled_tasks.pojo;

import lombok.Data;

@Data
public class QuartzBean {

    //任务名称
     private String jobID ;
    //执行任务类
     private String jobClass;
    //cron表达式
     private String cron;
}
java 复制代码
package com.juyuan.api.scheduled_tasks.jop;

import org.quartz.*;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;

public class SimpleTask extends QuartzJobBean {

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException{
        JobDetail jobDetail = jobExecutionContext.getJobDetail();
        JobKey key = jobDetail.getKey();
        System. out.println("任务名称为:"+key.getName()+",执行时间为:"+ LocalDateTime.now());
        System.out.println("=======================添加数据===================================");
    }

}
java 复制代码
package com.juyuan.api.scheduled_tasks.utils;

import com.juyuan.api.scheduled_tasks.pojo.QuartzBean;
import org.quartz.*;
import org.quartz.impl.matchers.GroupMatcher;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

public class QuartzUtils {

    /*
     *创建定时任务
     *@param scheduler 调度器
     *@param quartzBean 定时任务信息类
     */
    @Bean
    public static void createScheduleJob(Scheduler scheduler, QuartzBean quartzBean){
        try {
            Class<? extends Job> aClass = (Class<? extends Job>) Class.forName(quartzBean.getJobClass());
            JobDetail build = JobBuilder.newJob(aClass).withIdentity(quartzBean.getJobID()).build();
            //表达式调度构建器
            CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(quartzBean.getCron());
            //按新的cronExpression表达式构建一个新的trigger
            CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(quartzBean.getJobID()).withSchedule(cronScheduleBuilder).build();
            scheduler.scheduleJob(build,trigger);
        } catch (ClassNotFoundException | SchedulerException e) {
            throw new RuntimeException(e);
        }
    }

    /*根据任务恢复定时任务
      @param scheduler 调度器
      任务名称* param jobName
      */
    public static void resumeScheduleJob(Scheduler scheduler, String jobName) {
        JobKey jobKey = JobKey.jobKey(jobName);
        try {
            scheduler.resumeJob(jobKey);
        } catch (SchedulerException e) {
            throw new RuntimeException("恢复定时任务失败" + e.getMessage());
        }
    }

    /**
     * 暂停定时任务
     */
    public static void pauseScheduleJob(Scheduler scheduler, String jobName) {
        JobKey jobKey = JobKey.jobKey(jobName);
        try {
            scheduler.pauseJob(jobKey);
        } catch (SchedulerException e) {
            throw new RuntimeException("暂停定时任务失败" + e.getMessage());
        }
    }

    /**
     * 立即执行定时任务
     */
    public static void runScheduleJob(Scheduler scheduler, String jobName) {
        JobKey jobKey = JobKey.jobKey(jobName);
        try {
            scheduler.triggerJob(jobKey);
        } catch (SchedulerException e) {
            throw new RuntimeException("立即执行定时任务失败" + e.getMessage());
        }
    }

    /**
     * 删除定时任务
     */
    public static void deleteScheduleJob(Scheduler scheduler, String jobName) {
        JobKey jobKey = JobKey.jobKey(jobName);
        try {
            scheduler.deleteJob(jobKey);
        } catch (SchedulerException e) {
            throw new RuntimeException("删除定时任务失败" + e.getMessage());
        }
    }
    /**
     * 获取所有定时任务
     *
     * @param scheduler 调度器
     * @return 返回所有定时任务列表
     */
    public static List<JobDetail> getAllScheduleJob(Scheduler scheduler) {
        try {
            // 获取所有的JobKeys
            Set<JobKey> jobKeys = scheduler.getJobKeys(GroupMatcher.anyGroup());

            // 创建一个列表来存储所有的JobDetail对象
            List<JobDetail> jobDetails = new ArrayList<>();

            // 遍历每个JobKey,获取对应的JobDetail
            for (JobKey jobKey : jobKeys) {
                JobDetail jobDetail = scheduler.getJobDetail(jobKey);
                jobDetails.add(jobDetail);
            }
            // 现在,jobDetails列表包含了所有的JobDetail对象
            // 您可以在这里对这些对象进行处理
            return jobDetails;
        } catch (SchedulerException e) {
            throw new RuntimeException("获取所有定时任务失败" + e.getMessage());
        }
    }

    /**
     * 获取所有正在运行的定时任务
     *
     * @param scheduler 调度器
     * @return 返回所有正在运行的定时任务列表
     */
    public static List<JobDetail> getRunningScheduleJob(Scheduler scheduler) {
        try {
            List<JobExecutionContext> executingJobs = scheduler.getCurrentlyExecutingJobs();
            List<JobDetail> jobDetails = new ArrayList<>();
            for (JobExecutionContext executingJob : executingJobs) {
                JobDetail jobDetail = executingJob.getJobDetail();
                jobDetails.add(jobDetail);
            }
            return jobDetails;
        } catch (SchedulerException e) {
            throw new RuntimeException("获取所有正在运行的定时任务失败" + e.getMessage());
        }
    }

    /**
     * 修改定时任务
     * @param scheduler 调度器
     */
    public static void updateScheduleJob(Scheduler scheduler, QuartzBean quartzBean) {
        //获取对应的jobKey
        TriggerKey triggerKey = TriggerKey.triggerKey(quartzBean.getJobID());
        //获取执行定时任务的执行方式
        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(quartzBean.getCron());
        try {
            //按新的cronExpression表达式重新构建trigger
           CronTrigger character= (CronTrigger)scheduler.getTrigger(triggerKey);
            character = character.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
            //按新的trigger重新设置job执行
            scheduler.rescheduleJob(triggerKey, character);
        } catch (SchedulerException e) {
            throw new RuntimeException(e);
        }
    }


}

三、controller 实现

java 复制代码
package com.juyuan.api.scheduled_tasks.controller;

import com.juyuan.api.park_enterprise_public_construction.entity.ActionPlan;
import com.juyuan.api.park_enterprise_public_construction.service.ActionPlanService;
import com.juyuan.api.scheduled_tasks.pojo.QuartzBean;
import com.juyuan.api.scheduled_tasks.utils.QuartzUtils;

import com.juyuan.framework.common.constants.WebConstant;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class QuartzBeanController {
    private final String PATH = WebConstant.API_PATH + "/quartz/";

    @Autowired
    private Scheduler scheduler;

    @Autowired
    private ActionPlanService actionPlanService;

    //新增执行定时任务
    @GetMapping(value = PATH + "add")
    public void add() {
        List<ActionPlan> list = actionPlanService.list();
        for (ActionPlan actionPlan : list) {
            QuartzBean quartzBean = new QuartzBean();
            quartzBean.setJobID(actionPlan.getId());
            quartzBean.setJobClass("com.juyuan.api.scheduled_tasks.jop.SimpleTask");
            quartzBean.setCron(actionPlan.getFrequency());
            QuartzUtils.createScheduleJob(scheduler,quartzBean);
        }
    }
    //暂停执行定时任务
    @GetMapping(value = PATH + "pause")
    public void pause() {
        QuartzUtils.pauseScheduleJob(scheduler,"2");
    }
    //恢复执行定时任务
    @GetMapping(value = PATH + "resume")
    public void resume() {
        QuartzUtils.resumeScheduleJob(scheduler,"1");
    }
    //删除执行定时任务
    @GetMapping(value = PATH + "delete")
    public void delete() {
        QuartzUtils.deleteScheduleJob(scheduler,"2");
    }
    //立即执行定时任务
    @GetMapping(value = PATH + "run")
    public void run() {
        QuartzUtils.runScheduleJob(scheduler,"2");
    }

    //获取所有定时任务
    // 获取所有定时任务的接口
    @GetMapping(value = PATH + "queryAll")
    public void queryAll() {
        // 获取所有定时任务列表
        List<JobDetail> allScheduleJob = QuartzUtils.getAllScheduleJob(scheduler);
        // 遍历所有定时任务
        allScheduleJob.forEach(jobDetail -> {
            // 打印任务名称
            System.out.println(jobDetail.getKey().getName());
            // 打印任务组名
           // System.out.println(jobDetail.getKey().getGroup());
            // 打印任务描述
           // System.out.println(jobDetail.getDescription());
            // 打印任务类名
           // System.out.println(jobDetail.getJobClass());
            // 打印任务数据映射
           // System.out.println(jobDetail.getJobDataMap());
        });
    }


    //修改执行定时任务
    @GetMapping(value = PATH + "update")
    public void update() {
        QuartzBean quartzBean = new QuartzBean();
        quartzBean.setCron("0/5 * * * *?");
        quartzBean.setJobID("2");
        QuartzUtils.updateScheduleJob(scheduler,quartzBean);
    }

}
相关推荐
儿时可乖了13 分钟前
使用 Java 操作 SQLite 数据库
java·数据库·sqlite
ruleslol14 分钟前
java基础概念37:正则表达式2-爬虫
java
xmh-sxh-131431 分钟前
jdk各个版本介绍
java
XINGTECODE1 小时前
海盗王集成网关和商城服务端功能golang版
开发语言·后端·golang
天天扭码1 小时前
五天SpringCloud计划——DAY2之单体架构和微服务架构的选择和转换原则
java·spring cloud·微服务·架构
程序猿进阶1 小时前
堆外内存泄露排查经历
java·jvm·后端·面试·性能优化·oom·内存泄露
FIN技术铺1 小时前
Spring Boot框架Starter组件整理
java·spring boot·后端
小曲程序1 小时前
vue3 封装request请求
java·前端·typescript·vue
凡人的AI工具箱1 小时前
15分钟学 Go 第 60 天 :综合项目展示 - 构建微服务电商平台(完整示例25000字)
开发语言·后端·微服务·架构·golang
陈王卜1 小时前
django+boostrap实现发布博客权限控制
java·前端·django