Springboot+Quartz动态定时框架简单使用

如果你不相信努力和时光,那么成果就会是第一个选择辜负你的。不要去否定你自己的过去,也不要用你的过去牵扯你现在的努力和对未来的展望。不是因为拥有希望你才去努力,而是去努力了,你才有可能看到希望的光芒。Springboot+Quartz动态定时框架简单使用,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

1.pom文件包

<dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
            <version>2.3.0</version>
            <exclusions>
                <exclusion>
                    <groupId>com.mchange</groupId>
                    <artifactId>c3p0</artifactId>
                </exclusion>
            </exclusions>
</dependency>

2.创建测试定时任务类TestJob1 /TestJob2

import org.quartz.*;

import java.util.Date;

/**
 * @Description 定时任务测试类
 */
public class TestJob1 implements Job {
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        System.out.println("定时任务1开始了:"+new Date());
    }

    /**
     * @Description: 定时任务job1
     * @Param [scheduler]
     * @Return: void
     **/
    public void startJob1(Scheduler scheduler) throws SchedulerException {
        // 通过JobBuilder构建JobDetail实例,JobDetail规定只能是实现Job接口的实例
        // JobDetail 是具体Job实例
        JobDetail jobDetail = JobBuilder.newJob(TestJob1.class)
                .withIdentity("job1", "group1")
                .build();
        // 基于表达式构建触发器 //5s执行一次
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule("0/5 * * * * ?");
        // CronTrigger表达式触发器 继承于Trigger
        // TriggerBuilder 用于构建触发器实例
        CronTrigger cronTrigger = TriggerBuilder.newTrigger()
                .withIdentity("job1", "group1")
                .withDescription("测试任务描述job1")
                .withSchedule(cronScheduleBuilder)
                .build();
        scheduler.scheduleJob(jobDetail, cronTrigger);
    }
}

import org.quartz.*;

import java.util.Date;

/**
 * @Description 定时任务测试类
 */
public class TestJob2 implements Job {
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        System.out.println("定时任务2开始了:"+new Date());
    }

    /**
     * @Description: 定时任务job2
     * @Param [scheduler]
     * @Return: void
     **/
    public void startJob2(Scheduler scheduler) throws SchedulerException {
        // 通过JobBuilder构建JobDetail实例,JobDetail规定只能是实现Job接口的实例
        // JobDetail 是具体Job实例
        JobDetail jobDetail = JobBuilder.newJob(TestJob2.class)
                .withIdentity("job2", "group2")
                .build();
        // 基于表达式构建触发器 //3s执行一次
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule("0/10 * * * * ?");
        // CronTrigger表达式触发器 继承于Trigger
        // TriggerBuilder 用于构建触发器实例
        CronTrigger cronTrigger = TriggerBuilder.newTrigger()
                .withIdentity("job2", "group2")
                .withDescription("测试任务描述job2")
                .withSchedule(cronScheduleBuilder)
                .build();
        scheduler.scheduleJob(jobDetail, cronTrigger);
    }
}

3. Scheduler注入配置类

import lombok.extern.slf4j.Slf4j;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;

/**
 * @Description Scheduler 注入
 * 这里采用监听spring容器加载完毕后事件,启动任务调用
 * 将Scheduler交给spring初始化管理
 */
@Slf4j
@Configuration
public class ApplicationStartQuartzJobListener implements ApplicationListener<ContextRefreshedEvent> {
    @Autowired
    private QuartzSchedulerUtil quartzSchedulerUtil;

    /**
     * 初始启动quartz
     */
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        try {
            quartzSchedulerUtil.startAllJob();
            log.info("任务已经启动...");
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    /**
     * 初始注入scheduler
     *
     * @throws SchedulerException
     */
    @Bean
    public Scheduler scheduler() throws SchedulerException {
        SchedulerFactory schedulerFactoryBean = new StdSchedulerFactory();
        return schedulerFactoryBean.getScheduler();
    }

}

4.自定义定时任务实体QuartzJob 

import org.quartz.Job;

import java.io.Serializable;

/**
 * @Description 自定义定时任务实体
 */
public class QuartzJob implements Serializable {
    private static final long serialVersionUID = -5851989022924184181L;
    /**
     * 任务名
     */
    private String jobName;
    /**
     * 任务组名
     */
    private String jobGroupName;
    /**
     * 触发器名
     */
    private String triggerName;
    /**
     * 触发器组名
     */
    private String triggerGroupName;
    /**
     * 任务类名
     */
    private String jobClass;
    /**
     * corn表达式时间设置
     */
    private String cornTime;
    /**
     * 任务描述
     */
    private String jobDescription;

    public static long getSerialVersionUID() {
        return serialVersionUID;
    }

    public String getJobName() {
        return jobName;
    }

    public void setJobName(String jobName) {
        this.jobName = jobName;
    }

    public String getJobGroupName() {
        return jobGroupName;
    }

    public void setJobGroupName(String jobGroupName) {
        this.jobGroupName = jobGroupName;
    }

    public String getTriggerName() {
        return triggerName;
    }

    public void setTriggerName(String triggerName) {
        this.triggerName = triggerName;
    }

    public String getTriggerGroupName() {
        return triggerGroupName;
    }

    public void setTriggerGroupName(String triggerGroupName) {
        this.triggerGroupName = triggerGroupName;
    }

    public String getJobClass() {
        return jobClass;
    }

    public void setJobClass(String jobClass) {
        this.jobClass = jobClass;
    }

    public String getCornTime() {
        return cornTime;
    }

    public void setCornTime(String cornTime) {
        this.cornTime = cornTime;
    }

    public String getJobDescription() {
        return jobDescription;
    }

    public void setJobDescription(String jobDescription) {
        this.jobDescription = jobDescription;
    }
}

5.定时任务调度工具类QuartzSchedulerUtil 

import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.util.Date;
import java.util.HashMap;
import java.util.TimeZone;

/**
 * @Description 定时任务调度工具类
 */
@Configuration
public class QuartzSchedulerUtil {
    // 任务调度
    @Autowired
    private Scheduler scheduler;


    /**
     * @Description: 开始执行所有任务
     * @Param []
     * @Return: void
     **/
    public void startAllJob() throws SchedulerException {
        TestJob1 testJob1 = new TestJob1();
        testJob1.startJob1(scheduler);
        scheduler.start();
    }


    /**
     * @Description: 获取Job信息
     * @Param [triggerName:触发器名, triggerGroupName:触发器组名]
     * @Return: java.lang.String
     **/
    public HashMap<Object, Object> getJobInfo(String triggerName, String triggerGroupName) throws SchedulerException {
        TriggerKey key = new TriggerKey(triggerName, triggerGroupName);
        CronTrigger cronTrigger = (CronTrigger) scheduler.getTrigger(key);
        String cronExpression = cronTrigger.getCronExpression();
        TimeZone timeZone = cronTrigger.getTimeZone();
        String description = cronTrigger.getDescription();
        JobKey jobKey = cronTrigger.getJobKey();
        TriggerKey triggerKey = cronTrigger.getKey();
        String state = scheduler.getTriggerState(triggerKey).name();

        HashMap<Object, Object> map = new HashMap<>();
        map.put("corn表达式", cronExpression);
        map.put("状态", state);
        map.put("时区", timeZone);
        map.put("任务描述", description);
        map.put("jobKey", jobKey);
        map.put("triggerKey", triggerKey);
        return map;
    }

    /**
     * @Description: 修改某个任务的执行时间
     * @Param [triggerName:触发器名, triggerGroupName:触发器组名, cornTime:corn表达式]
     * @Return: boolean
     **/
    public boolean modifyJob(String triggerName, String triggerGroupName, String cornTime) throws SchedulerException {
        Date date = null;
        TriggerKey triggerKey = new TriggerKey(triggerName, triggerGroupName);
        CronTrigger cronTrigger = (CronTrigger) scheduler.getTrigger(triggerKey);
        String oldTime = cronTrigger.getCronExpression();
        if (!oldTime.equalsIgnoreCase(cornTime)) {
            CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(cornTime);
            CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(triggerName, triggerGroupName)
                    .withSchedule(cronScheduleBuilder).build();
            date = scheduler.rescheduleJob(triggerKey, trigger);
        }
        return date != null;
    }

    /**
     * @Description: 暂停所有任务
     * @Param []
     * @Return: void
     **/
    public void pauseAllJob() throws SchedulerException {
        scheduler.pauseAll();
    }

    /**
     * @Description: 暂停某个任务
     * @Param [jobName 任务名, jobGroupName 任务组名]
     * @Return: void
     **/
    public void pauseJob(String jobName, String jobGroupName) throws SchedulerException {
        JobKey jobKey = JobKey.jobKey(jobName, jobGroupName);
        JobDetail jobDetail = scheduler.getJobDetail(jobKey);
        if (jobDetail == null)
            return;
        scheduler.pauseJob(jobKey);
    }

    /**
     * @Description: 恢复所有任务
     * @Param []
     * @Return: void
     **/
    public void resumeAllJob() throws SchedulerException {
        scheduler.resumeAll();
    }

    /**
     * @Description: 恢复某个任务
     * @Param [jobName 任务名, jobGroupName 任务组名]
     * @Return: void
     **/
    public void resumeJob(String jobName, String jobGroupName) throws SchedulerException {
        JobKey jobKey = JobKey.jobKey(jobName, jobGroupName);
        JobDetail jobDetail = scheduler.getJobDetail(jobKey);
        if (jobDetail == null)
            return;
        scheduler.resumeJob(jobKey);
    }

    /**
     * @Description: 删除某个任务
     * @Param [jobName 任务名, jobGroupName 任务组名]
     * @Return: void
     **/
    public void deleteJob(String jobName, String jobGroupName) throws SchedulerException {
        JobKey jobKey = new JobKey(jobName, jobGroupName);
        JobDetail jobDetail = scheduler.getJobDetail(jobKey);
        if (jobDetail == null)
            return;
        scheduler.deleteJob(jobKey);
    }

    /**
     * @Description: 创建某个定时任务并执行
     * @Param [
     * jobName 任务名,
     * jobGroupName 任务组名,
     * triggerName 触发器名,
     * triggerGroupName 触发器组名,
     * jobClass 任务类名,
     * cornTime corn表达式时间设置,
     * jobDescription 任务描述
     * ]
     * @Return: void
     **/
    public void addStartJob(QuartzJob quartzJob) throws SchedulerException, ClassNotFoundException {
        String jobName = quartzJob.getJobName();
        String jobGroupName = quartzJob.getJobGroupName();
        String triggerName = quartzJob.getTriggerName();
        String triggerGroupName = quartzJob.getTriggerGroupName();
        String jobClass = quartzJob.getJobClass();
        String cornTime = quartzJob.getCornTime();
        String jobDescription = quartzJob.getJobDescription();
        //判断是否已经有这个任务
        TriggerKey triggerKey = TriggerKey.triggerKey(jobName, triggerGroupName);
        CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
        Class aClass = Class.forName(jobClass);
        //通过JobBuilder构建JobDetail实例,JobDetail规定只能是实现Job接口的实例
        //JobDetail 是具体Job实例
        if (null == trigger) {
            JobDetail jobDetail = JobBuilder.newJob(aClass)
                    .withIdentity(jobName, jobGroupName)
                    .build();
            //基于表达式构建触发器
            CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(cornTime);
            //CronTrigger表达式触发器 继承于Trigger
            //TriggerBuilder 用于构建触发器实例
            CronTrigger cronTrigger = TriggerBuilder.newTrigger()
                    .withIdentity(triggerName, triggerGroupName)
                    .withDescription(jobDescription)
                    .withSchedule(cronScheduleBuilder)
                    .build();
            //开始执行
            scheduler.scheduleJob(jobDetail, cronTrigger);
            if (!scheduler.isShutdown()) {
                scheduler.start();
            }
        } else {
            //Trigger已存在,那么更新相应的定时设置
            //表达式调度构建器
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cornTime);
            //按新的cronExpression表达式重新构建trigger
            trigger = trigger.getTriggerBuilder()
                    .withIdentity(triggerKey)
                    .withSchedule(scheduleBuilder)
                    .build();
            //按新的trigger重新设置job执行
            scheduler.rescheduleJob(triggerKey, trigger);
        }
    }
}

6.动态定时任务控制器JobController 

import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import com.xkr.lsos.common.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;

@RestController
@RequestMapping("/job")
public class JobController {
    @Autowired
    private QuartzSchedulerUtil quartzSchedulerUtil;

    /**
     * 开始执行所有任务
     */
    @ApiOperation(value = "添加某个任务并执行")
    @PostMapping("/addStartJob")
    public void startQuartzJob(@RequestBody QuartzJob quartzJob) {
        try {
            quartzSchedulerUtil.addStartJob(quartzJob);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @Description: 获取Job信息
     * @Param [triggerName:触发器名, triggerGroupName:触发器组名]
     * @Return: java.lang.String
     **/
    @ApiOperation(value = "获取Job信息")
    @GetMapping(value = "/info")
    public Result<?> getQuartzJob(@RequestParam String triggerName, @RequestParam String triggerGroupName) {
        HashMap<Object, Object> info = null;
        try {
            info = quartzSchedulerUtil.getJobInfo(triggerName, triggerGroupName);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        return Result.OK(info);
    }

    /**
     * @Description: 修改某个任务的执行时间
     * @Param [triggerName:触发器名, triggerGroupName:触发器组名, cornTime:corn表达式]
     * @Return: boolean
     **/
    @ApiOperation(value = "修改某个任务的执行时间")
    @GetMapping(value = "/modify")
    public Result<?> modifyQuartzJob(@RequestParam String triggerName, @RequestParam String triggerGroupName, @RequestParam String cornTime) {
        boolean flag = true;
        try {
            flag = quartzSchedulerUtil.modifyJob(triggerName, triggerGroupName, cornTime);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        return Result.OK(flag);
    }

    /**
     * 开始执行所有任务
     */
    @ApiOperation(value = "开始执行所有任务")
    @GetMapping(value = "/startAll")
    public void startQuartzAllJob() {
        try {
            quartzSchedulerUtil.startAllJob();
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    /**
     * @Description: 恢复所有任务
     * @Param []
     * @Return: void
     **/
    @ApiOperation(value = "恢复所有任务")
    @GetMapping(value = "/resumeAll")
    public void resumeAllJob() {
        try {
            quartzSchedulerUtil.resumeAllJob();
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    /**
     * @Description: 恢复某个任务
     * @Param [jobName 任务名, jobGroupName 任务组名]
     * @Return: void
     **/
    @ApiOperation(value = "恢复某个任务")
    @GetMapping(value = "/resume")
    public void resumeJob(@RequestParam String jobName, @RequestParam String jobGroupName) {
        try {
            quartzSchedulerUtil.resumeJob(jobName, jobGroupName);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    /**
     * @Description: 暂停某个任务
     * @Param [jobName 任务名, jobGroupName 任务组名]
     * @Return: void
     **/
    @ApiOperation(value = "暂停某个任务")
    @GetMapping(value = "/pause")
    public void pauseQuartzJob(@RequestParam String jobName, @RequestParam String jobGroupName) {
        try {
            quartzSchedulerUtil.pauseJob(jobName, jobGroupName);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    /**
     * @Description: 暂停所有任务
     * @Param []
     * @Return: void
     **/
    @ApiOperation(value = "暂停所有任务")
    @GetMapping(value = "/pauseAll")
    public void pauseAllQuartzJob() {
        try {
            quartzSchedulerUtil.pauseAllJob();
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    /**
     * @Description: 删除某个任务
     * @Param [jobName:任务名, jobGroupName:任务组名]
     * @Return: void
     **/
    @ApiOperation(value = "删除某个任务")
    @GetMapping(value = "/delete")
    public void deleteJob(@RequestParam String jobName, @RequestParam String jobGroupName) {
        try {
            quartzSchedulerUtil.deleteJob(jobName, jobGroupName);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }
}

结果: 

定时任务1开始了:Thu Jun 16 16:41:30 CST 2022
定时任务2开始了:Thu Jun 16 16:41:30 CST 2022
2022-06-16 16:41:32.448 [http-nio-9999-exec-4] INFO  com.xkr.lsos.annotation.aspect.LogAspect:327 -[]  – RESPONSE_PARAM : {“result”:”time:0/5 * * * * ?,state:NORMAL”,”code”:200,”success”:true,”message”:”操作成功!”,”timestamp”:1655368892383}
2022-06-16 16:41:32.456 [http-nio-9999-exec-4] INFO  com.xkr.lsos.annotation.aspect.LogAspect:312 -[]  – INTERFACE_ELAPSED_TIME : -73 ms
定时任务1开始了:Thu Jun 16 16:41:35 CST 2022
定时任务1开始了:Thu Jun 16 16:41:40 CST 2022
定时任务2开始了:Thu Jun 16 16:41:40 CST 2022
定时任务1开始了:Thu Jun 16 16:41:45 CST 2022

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/192795.html

(0)
飞熊的头像飞熊bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!