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);
    }

}
相关推荐
星河梦瑾36 分钟前
SpringBoot相关漏洞学习资料
java·经验分享·spring boot·安全
黄名富39 分钟前
Redis 附加功能(二)— 自动过期、流水线与事务及Lua脚本
java·数据库·redis·lua
love静思冥想41 分钟前
JMeter 使用详解
java·jmeter
言、雲43 分钟前
从tryLock()源码来出发,解析Redisson的重试机制和看门狗机制
java·开发语言·数据库
TT哇1 小时前
【数据结构练习题】链表与LinkedList
java·数据结构·链表
机器之心1 小时前
图学习新突破:一个统一框架连接空域和频域
人工智能·后端
Yvemil71 小时前
《开启微服务之旅:Spring Boot 从入门到实践》(三)
java
Anna。。1 小时前
Java入门2-idea 第五章:IO流(java.io包中)
java·开发语言·intellij-idea
计算机学长felix2 小时前
基于SpringBoot的“交流互动系统”的设计与实现(源码+数据库+文档+PPT)
spring boot·毕业设计
.生产的驴2 小时前
SpringBoot 对接第三方登录 手机号登录 手机号验证 微信小程序登录 结合Redis SaToken
java·spring boot·redis·后端·缓存·微信小程序·maven