阅读 2297

SpringBoot轻松整合Quartz

从今天起,撸起袖子跟着我加油干


提示:如有疑问请私信联系、下方有源代码地址,请自行拿取

前言

使用Spring Boot 可以非常方便、快速搭建项目,使我们不用关心框架之间的兼容性,适用版本等各种问题,我们想使用任何东西,仅仅添加一个配置就可以。


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

一、技术介绍

1.Quartz是什么?

Quartz 是一个完全由 Java 编写的开源作业调度框架,为在 Java 应用程序中进行作业调度提供了简单却强大的机制。

Quartz 可以与 J2EE 与 J2SE 应用程序相结合也可以单独使用。

Quartz 允许程序开发人员根据时间的间隔来调度作业。

Quartz 实现了作业和触发器的多对多的关系,还能把多个作业与不同的触发器关联。

二、使用步骤

1.引入maven库

代码如下(示例):

	 	<parent>
	        <groupId>org.springframework.boot</groupId>
	        <artifactId>spring-boot-starter-parent</artifactId>
	        <version>2.4.1</version>
	        <relativePath/>
	    </parent>
        <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-quartz</artifactId>
        </dependency>
    </dependencies>
复制代码

2.Quartz具体使用示例

IJob接口类:

package com.hyh.quartz;


/**
 * IJOB接口
 *
 * @Author: heyuhua
 * @Date: 2021/1/11 14:54
 */
public interface IJob {
    /**
     * 开始任务
     *
     * @param name
     * @param group
     * @param cron
     * @param clazz
     */
    void start(String name, String group, String cron, Class clazz);

    /**
     * 修改任务
     *
     * @param name
     * @param group
     * @param time
     * @return
     */
    boolean modify(String name, String group, String time);


    /**
     * 暂停
     *
     * @param name
     * @param group
     */
    void stop(String name, String group);

    /**
     * 暂停所有
     */
    void stopAll();

    /**
     * 恢复任务
     *
     * @param name
     * @param group
     */
    void resume(String name, String group);


    /**
     * 恢复所有
     */
    void resumeAll();

    /**
     * 删除任务
     *
     * @param name
     * @param group
     */
    void delete(String name, String group);
}






复制代码

Job接口类:

package com.hyh.quartz.service;

import com.hyh.quartz.IJob;

/**
 * job 接口
 *
 * @Author: heyuhua
 * @Date: 2021/1/11 14:46
 */
public interface JobService extends IJob {


    /**
     * 获取任务信息
     *
     * @param name
     * @param group
     * @return
     */
    String get(String name, String group);

}






复制代码

Job接口实现类:

package com.hyh.quartz.service.impl;

import com.hyh.quartz.service.JobService;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @Author: heyuhua
 * @Date: 2021/1/11 14:55
 */
@Service
public class JobServiceImpl implements JobService {

    /**
     * 日志
     */
    private static final Logger LOG = LoggerFactory.getLogger(JobServiceImpl.class);

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


    @Override
    public void start(String name, String group, String cron, Class clazz) {
        try {
            // 通过JobBuilder构建JobDetail实例,JobDetail规定只能是实现Job接口的实例
            // JobDetail 是具体Job实例
            JobDetail jobDetail = JobBuilder.newJob(clazz).withIdentity(name, group).build();
            // 基于表达式构建触发器
            CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(cron);
            // CronTrigger表达式触发器 继承于Trigger
            // TriggerBuilder 用于构建触发器实例
            CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity(name, group)
                    .withSchedule(cronScheduleBuilder).build();
            scheduler.scheduleJob(jobDetail, cronTrigger);
            scheduler.start();
            LOG.info(" job 【name=" + name + "】【group=" + group + "】 has start ");
        } catch (SchedulerException schedulerException) {
            LOG.error("任务启动异常", schedulerException);
        }
    }

    @Override
    public boolean modify(String name, String group, String time) {
        Date date = null;
        try {
            TriggerKey triggerKey = new TriggerKey(name, group);
            CronTrigger cronTrigger = (CronTrigger) scheduler.getTrigger(triggerKey);
            String oldTime = cronTrigger.getCronExpression();
            if (!oldTime.equalsIgnoreCase(time)) {
                CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(time);
                CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(name, group)
                        .withSchedule(cronScheduleBuilder).build();
                date = scheduler.rescheduleJob(triggerKey, trigger);
            }
            LOG.info(" job 【name=" + name + "】【group=" + group + "】 modify ");
        } catch (SchedulerException schedulerException) {
            LOG.error("任务更新异常", schedulerException);
        }
        return date != null;
    }

    @Override
    public void stop(String name, String group) {
        try {
            JobKey jobKey = new JobKey(name, group);
            JobDetail jobDetail = scheduler.getJobDetail(jobKey);
            if (jobDetail == null)
                return;
            scheduler.pauseJob(jobKey);
            LOG.info(" job 【name=" + name + "】【group=" + group + "】 is stop");
        } catch (SchedulerException schedulerException) {
            LOG.error("任务停止异常", schedulerException);
        }
    }

    @Override
    public void stopAll() {
        try {
            scheduler.pauseAll();
            LOG.info(" all job is stop");
        } catch (SchedulerException schedulerException) {
            LOG.error("停止全部任务时异常", schedulerException);

        }
    }

    @Override
    public void resume(String name, String group) {
        try {
            JobKey jobKey = new JobKey(name, group);
            JobDetail jobDetail = scheduler.getJobDetail(jobKey);
            if (jobDetail == null)
                return;
            scheduler.resumeJob(jobKey);
            LOG.info(" job 【name=" + name + "】【group=" + group + "】 is resume");
        } catch (SchedulerException schedulerException) {
            LOG.error("任务恢复时异常", schedulerException);

        }
    }

    @Override
    public void resumeAll() {
        try {
            scheduler.resumeAll();
            LOG.info(" all job is resume");
        } catch (SchedulerException schedulerException) {
            LOG.error("恢复所有任务时异常", schedulerException);
        }
    }

    @Override
    public void delete(String name, String group) {
        try {
            JobKey jobKey = new JobKey(name, group);
            JobDetail jobDetail = scheduler.getJobDetail(jobKey);
            if (jobDetail == null)
                return;
            scheduler.deleteJob(jobKey);
            LOG.info(" job 【name=" + name + "】【group=" + group + "】  has delete");
        } catch (SchedulerException schedulerException) {
            LOG.error("任务删除时异常", schedulerException);
        }
    }

    @Override
    public String get(String name, String group) {
        try {
            TriggerKey triggerKey = new TriggerKey(name, group);
            CronTrigger cronTrigger = (CronTrigger) scheduler.getTrigger(triggerKey);
            LOG.info(" job 【name=" + name + "】【group=" + group + "】 get");
            return String.format("time:%s,state:%s", cronTrigger.getCronExpression(),
                    scheduler.getTriggerState(triggerKey).name());
        } catch (SchedulerException schedulerException) {
            LOG.error("任务获取时异常", schedulerException);
        }
        return null;
    }
}







复制代码

Job工具助手类:

package com.hyh.quartz.helper;

import com.hyh.quartz.service.JobService;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

/**
 * JOB助手
 *
 * @Author: heyuhua
 * @Date: 2021/1/11 15:20
 */
@Component
public class JobHelper {

    /**
     * JOB服务
     */
    @Autowired
    private JobService jobService;

    /**
     * 任务启动
     *
     * @param name
     * @param group
     * @param cron
     * @param clazz
     */
    public void start(String name, String group, String cron, Class clazz) {
        Assert.notNull(name, "name is null");
        Assert.notNull(group, "group is null");
        Assert.notNull(cron, "cron is null");
        Assert.notNull(clazz, "clazz is null");
        jobService.start(name, group, cron, clazz);
    }

    /**
     * 任务更新
     *
     * @param name
     * @param group
     * @param time
     * @return
     * @throws SchedulerException
     */
    public boolean modify(String name, String group, String time) throws SchedulerException {
        Assert.notNull(name, "name is null");
        Assert.notNull(group, "group is null");
        Assert.notNull(time, "time is null");
        return jobService.modify(name, group, time);
    }

    /**
     * 任务停止
     *
     * @param name
     * @param group
     */
    public void stop(String name, String group) {
        Assert.notNull(name, "name is null");
        Assert.notNull(group, "group is null");
        jobService.stop(name, group);
    }

    /**
     * 停止所有任务
     */
    public void stopAll() {
        jobService.stopAll();
    }

    /**
     * 任务恢复
     *
     * @param name
     * @param group
     */
    public void resume(String name, String group) {
        Assert.notNull(name, "name is null");
        Assert.notNull(group, "group is null");
        jobService.resume(name, group);
    }

    /**
     * 恢复所有任务
     */
    public void resumeAll() {
        jobService.resumeAll();
    }

    /**
     * 任务删除
     *
     * @param name
     * @param group
     */
    public void delete(String name, String group) {
        Assert.notNull(name, "name is null");
        Assert.notNull(group, "group is null");
        jobService.delete(name, group);
    }

    /**
     * 获取任务信息
     *
     * @param name
     * @param group
     * @return
     */
    public String get(String name, String group) {
        Assert.notNull(name, "name is null");
        Assert.notNull(group, "group is null");
        return jobService.get(name, group);
    }


}






复制代码

3.配置文件

代码如下(示例):

server:
  port: 8088


复制代码

4.单元测试

测试代码如下(示例):

package com.hyh.core.test;

import com.hyh.core.test.base.HyhTest;
import org.junit.Test;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

/**
 * 任务测试类
 *
 * @Author: heyuhua
 * @Date: 2021/1/11 15:34
 */
public class QuartzTest extends HyhTest {


    @Test
    public void testStartJob() throws InterruptedException {
        //测试时需要开启HyhBootApplication
        HttpHeaders headers = new HttpHeaders();
        //设置请求媒体数据类型
        headers.setContentType(MediaType.APPLICATION_JSON);
        //设置返回媒体数据类型
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        HttpEntity<String> formEntity = new HttpEntity<String>(null, headers);
        restTemplate.postForObject("http://localhost:8088/hyh/startJob", formEntity,String.class);
    }

    @Test
    public void testDeleteJob(){
        //测试时需要开启HyhBootApplication
        HttpHeaders headers = new HttpHeaders();
        //设置请求媒体数据类型
        headers.setContentType(MediaType.APPLICATION_JSON);
        //设置返回媒体数据类型
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        HttpEntity<String> formEntity = new HttpEntity<String>(null, headers);
        restTemplate.postForObject("http://localhost:8088/hyh/deleteJob", formEntity,String.class);
    }


    @Test
    @Override
    public void test() {
        System.out.println("---quartz测试---");
    }


}
//controller层使用
   @RequestMapping(value = "startJob",method = {RequestMethod.POST,RequestMethod.GET})
    public void startJob(){
        String name = "hyh-name", group = "hyh-group", cron = "*/5 * * * * ?";
        jobHelper.start(name, group, cron, HyhJob.class);
    }

    @RequestMapping(value = "deleteJob",method = {RequestMethod.POST,RequestMethod.GET})
    public void deleteJob(){
        String name = "hyh-name", group = "hyh-group", cron = "*/5 * * * * ?";
        jobHelper.delete(name, group);
    }


复制代码

总结

更多用法请点击下方查看源码,是不是感觉很简单?关注我带你揭秘更多Quartz高级用法

源码地址:点此查看源码.

文章分类
后端
文章标签