spring boot 整合quarkz 实现开启关闭定时任务

效果图片:

在springboot2.0后官方添加了Quartz框架的依赖,所以只需要在pom文件当中引入

<!--引入quartz定时框架-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-quartz</artifactId>
        </dependency>

 第一步 创建一个定时任务相关实体类用于保存定时任务相关信息到数据库当中

package com.gpdi.operatingunit.entity.quartz;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;

/**
 * @description: 定时任务
 * @author: Lxq
 * @date: 2019/10/28 17:16
 */
@TableName("quartz_job")
public class QuartzJob {

    /**
     * 定时任务id
     */
    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;
    /**
     * 定时任务名称
     */
    private String jobName;
    /**
     * 定时任务执行类
     */
    private String jobClass;
    /**
     * 定时任务状态
     */
    private Integer status;
    /**
     * 定时任务表达式
     */
    private String cronExpression;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getJobName() {
        return jobName;
    }

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

    public String getJobClass() {
        return jobClass;
    }

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

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    public String getCronExpression() {
        return cronExpression;
    }

    public void setCronExpression(String cronExpression) {
        this.cronExpression = cronExpression;
    }
}

第二步 创建定时任务暂停,修改,启动,单次启动工具类

package com.gpdi.operatingunit.utils;

import com.gpdi.operatingunit.entity.quartz.QuartzJob;
import org.quartz.*;

/**
 * @description: 定时器任务工具类
 * @author: Lxq
 * @date: 2019/10/28 17:12
 */
public class QuartzUtils {

    /**
     * 创建定时任务 定时任务创建之后默认启动状态
     *
     * @param scheduler  调度器
     * @param quartzBean 定时任务信息类
     */
    public static void createScheduleJob(Scheduler scheduler, QuartzJob quartzBean) throws ClassNotFoundException, SchedulerException {

        // 获取到定时任务的执行类  必须是类的绝对路径名称
        // 定时任务类需要是job类的具体实现 QuartzJobBean是job的抽象类。
        Class<? extends Job> jobClass = (Class<? extends Job>) Class.forName(quartzBean.getJobClass());
        // 构建定时任务信息
        JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(quartzBean.getJobName()).build();
        // 设置定时任务执行方式
        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(quartzBean.getCronExpression());
        //构建触发器trigger
        CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(quartzBean.getJobName()).withSchedule(scheduleBuilder).build();
        scheduler.scheduleJob(jobDetail, trigger);
    }

    /**
     * 根据任务名称暂停定时任务
     *
     * @param scheduler 调度器
     * @param jobName   定时任务名称
     */
    public static void pauseScheduleJob(Scheduler scheduler, String jobName) throws SchedulerException {
        JobKey jobKey = JobKey.jobKey(jobName);
        scheduler.pauseJob(jobKey);
    }

    /**
     * 根据任务名称恢复定时任务
     *
     * @param scheduler 调度器
     * @param jobName   定时任务名称
     */
    public static void resumeScheduleJob(Scheduler scheduler, String jobName) throws SchedulerException {
        JobKey jobKey = JobKey.jobKey(jobName);
        scheduler.resumeJob(jobKey);
    }

    /**
     * 根据任务名称立即运行一次定时任务
     *
     * @param scheduler 调度器
     * @param jobName   定时任务名称
     */
    public static void runOnce(Scheduler scheduler, String jobName) throws SchedulerException {
        JobKey jobKey = JobKey.jobKey(jobName);
        scheduler.triggerJob(jobKey);
    }

    /**
     * 更新定时任务
     *
     * @param scheduler  调度器
     * @param quartzBean 定时任务信息类
     */
    public static void updateScheduleJob(Scheduler scheduler, QuartzJob quartzBean) throws SchedulerException {
        //获取到对应任务的触发器
        TriggerKey triggerKey = TriggerKey.triggerKey(quartzBean.getJobName());
        //设置定时任务执行方式
        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(quartzBean.getCronExpression());
        //重新构建任务的触发器trigger
        CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
        trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
        //重置对应的job
        scheduler.rescheduleJob(triggerKey, trigger);

    }

    /**
     * 根据定时任务名称从调度器当中删除定时任务
     *
     * @param scheduler 调度器
     * @param jobName   定时任务名称
     */
    public static void deleteScheduleJob(Scheduler scheduler, String jobName) throws SchedulerException {
        JobKey jobKey = JobKey.jobKey(jobName);
        scheduler.deleteJob(jobKey);
    }
}

第三步 创建一个定时任务

package com.gpdi.operatingunit.controller.quartz.task;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.util.Date;

/**
 * @description: 区县报表任务调度
 * @author: Lxq
 * @date: 2019/10/29 11:15
 */
public class CountryTask extends QuartzJobBean{
    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        System.out.println("区县报表任务调度");
        System.out.println("动态的定时任务执行时间:"+new Date().toLocaleString());
    }
}

第四步 操作任务

package com.gpdi.operatingunit.controller.quartz;

import com.gpdi.operatingunit.config.R;
import com.gpdi.operatingunit.entity.quartz.QuartzJob;
import com.gpdi.operatingunit.service.quartz.QuartzJobService;
import com.gpdi.operatingunit.utils.QuartzUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.quartz.CronExpression;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.impl.matchers.GroupMatcher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Set;

/**
 * @description: 任务调度
 * @author: Lxq
 * @date: 2019/10/28 17:11
 */
@RestController
@RequestMapping("/quartz/")
@Api(description = "任务调度控制器")
public class QuartzController {

    /**
     * 注入任务调度
     */
    @Autowired
    private Scheduler scheduler;

    @Autowired
    private QuartzJobService quartzJobService;


    @RequestMapping(value = "/getJobList", method = {RequestMethod.GET})
    @ApiOperation("查询所有任务列表信息")
    public R getJobList() {
        List<QuartzJob> quartzJobs = quartzJobService.queryQuartzJob();
        return R.ok(quartzJobs);
    }
    @RequestMapping("/createJob")
    public String createJob() {
        try {
            QuartzJob quartzBean = new QuartzJob();
            //进行测试所以写死
            quartzBean.setJobClass("com.gpdi.quartzTask.CountryTask ");
            quartzBean.setJobName("test1");
            quartzBean.setCronExpression("*/1 * * * * ?");
            QuartzUtils.createScheduleJob(scheduler, quartzBean);
        } catch (ClassNotFoundException e) {
            System.out.println("定时任务类路径出错:请输入类的绝对路径");
        } catch (SchedulerException e) {
            System.out.println("创建定时任务出错:" + e.getMessage());
        }
        return "创建成功";
    }

    @RequestMapping(value = "/pauseJob", method = {RequestMethod.POST})
    @ApiOperation("停止定时任务")
    public R pauseJob(String jobName, Integer id) {
        try {
            // 暂停任务
            QuartzUtils.pauseScheduleJob(scheduler, jobName);
            // 修改状态值
            QuartzJob quartzJob = new QuartzJob();
            quartzJob.setId(id);
            quartzJob.setStatus(0);
            quartzJobService.updateQuartzJobStatus(quartzJob);
        } catch (Exception e) {
            return R.ok("error");
        }
        return R.ok("success");

    }


    @RequestMapping(value = "/resumJob", method = {RequestMethod.POST})
    public R resumJob(String jobName, Integer id, String jobClass, String cronExpression) {
        try {
            // 判断是否存在该定时任务
            Boolean flag = true;
            Set<JobKey> jobKeys = scheduler.getJobKeys(GroupMatcher.anyGroup());
            JobKey job = new JobKey(jobName);
            if (jobKeys.contains(job)) {
                flag = false;
            }
            if (flag) {
                // 创建新的任务
                QuartzJob quartzJob = new QuartzJob();
                quartzJob.setJobClass(jobClass);
                quartzJob.setJobName(jobName);
                quartzJob.setCronExpression(cronExpression);
                QuartzUtils.createScheduleJob(scheduler, quartzJob);
                quartzJob.setStatus(1);
                quartzJob.setId(id);
                quartzJobService.updateQuartzJobStatus(quartzJob);

            } else {
                // 重启
                QuartzUtils.resumeScheduleJob(scheduler, jobName);
                // 修改状态值
                QuartzJob quartzJob = new QuartzJob();
                quartzJob.setId(id);
                quartzJob.setStatus(1);
                quartzJobService.updateQuartzJobStatus(quartzJob);
            }

        } catch (Exception e) {
            return R.ok("error");
        }
        return R.ok("success");
    }

    @RequestMapping(value = "/runOnceJob", method = {RequestMethod.POST})
    public R runOnceJob(String jobName, String jobClass, String cronExpression,Integer id) {
        try {
            Set<JobKey> jobKeys = scheduler.getJobKeys(GroupMatcher.anyGroup());
            JobKey jobKey = new JobKey(jobName);
            if (jobKeys.contains(jobKey)){
                QuartzUtils.runOnce(scheduler, jobName);
            }else {
                QuartzJob quartzBean = new QuartzJob();
                quartzBean.setJobClass(jobClass);
                quartzBean.setJobName(jobName);
                quartzBean.setCronExpression(cronExpression);
                // 创建
                QuartzUtils.createScheduleJob(scheduler, quartzBean);
                // 停止
                QuartzUtils.pauseScheduleJob(scheduler,quartzBean.getJobName());
                //执行一次
                QuartzUtils.runOnce(scheduler, jobName);

            }
        } catch (Exception e) {
            return R.ok("error");
        }
        return R.ok("success");
    }

    @RequestMapping(value = "/updateJob", method = {RequestMethod.POST})
    public R updateJob(String jobName, Integer id, String jobClass, String cronExpression) throws SchedulerException {
        QuartzJob quartzJobById = quartzJobService.getQuartzJobById(id);
        boolean validExpression = CronExpression.isValidExpression(cronExpression);
        Set<JobKey> jobKeys = scheduler.getJobKeys(GroupMatcher.anyGroup());
        if (validExpression) {
            JobKey jobKey = new JobKey(jobName);
            // 是否已经被创建
            if (jobKeys.contains(jobKey)){
                // 是否是运行状态
                QuartzJob quartzJob = new QuartzJob();
                quartzJob.setId(id);
                quartzJob.setJobName(jobName);
                quartzJob.setJobClass(jobClass);
                quartzJob.setCronExpression(cronExpression);
                if(quartzJobById.getStatus() == 1){
                    QuartzUtils.updateScheduleJob(scheduler,quartzJob);
                }else {
                    QuartzUtils.updateScheduleJob(scheduler,quartzJob);
                    QuartzUtils.pauseScheduleJob(scheduler,quartzJob.getJobName());
                }
                quartzJobService.updateQuartzJobStatus(quartzJob);
            }else {
                // 还没创建该任务,直接修改数据库数据
                QuartzJob quartzJob = new QuartzJob();
                quartzJob.setId(id);
                quartzJob.setCronExpression(cronExpression);
                quartzJobService.updateQuartzJobStatus(quartzJob);
            }
            return R.ok("success");
        }else {
            return R.ok("cornError");
        }
    }

}

 

发布了36 篇原创文章 · 获赞 23 · 访问量 2022
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 游动-白 设计师: 上身试试

分享到微信朋友圈

×

扫一扫,手机浏览