1. 程式人生 > >Quartz+Spring Boot實現動態管理定時任務

Quartz+Spring Boot實現動態管理定時任務

varchar 設置 ica key equals 修改 lean queryall 觸發器

項目實踐過程中碰到一個動態管理定時任務的需求:針對每個人員進行信息的定時更新,具體更新時間可隨時調整、啟動、暫定等。

思路

將每個人員信息的定時配置保存到數據庫中,這樣實現了任務的動態展示和管理。任務的每一次新增或變更,都會去數據庫變更信息。

設置一個統一的任務管理器,專門負責動態任務的增刪改查。

POM依賴

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>dynamic-quartz</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>dynamic-quartz</name>
    <description>動態定時任務管理</description>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
       <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.1.1</version>
        </dependency>
        <!-- jdbc driver -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.44</version>
        </dependency>
        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
            <version>2.3.0</version>
        </dependency>
    </dependencies>
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
</project>

application.yml

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/wujiwen
    username: root
    password: root
    driver-class-name: com.mysql.jdbc.Driver

  profiles:
      active: dev

logback-spring.xml

<configuration>
    <jmxConfigurator />
    <appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
        <layout class="ch.qos.logback.classic.PatternLayout">
            <pattern>%date [%thread] %-5level %logger{80} - %msg%n</pattern>
        </layout>
    </appender>

    <logger name="org.springframework">
        <level value="ERROR" />
    </logger>
    <logger name="org.mybatis">
        <level value="ERROR" />
    </logger>
    <logger name="java.sql.Connection">
        <level value="DEBUG" />
    </logger>
    <logger name="java.sql.Statement">
        <level value="DEBUG" />
    </logger>
    <logger name="java.sql.PreparedStatement">
        <level value="DEBUG" />
    </logger>
    <logger name="java.sql.ResultSet">
        <level value="DEBUG"/>
    </logger>
    <logger name="org.apache.http">
        <level value="INFO" />
    </logger>
    <logger name="org.quartz">
        <level value="INFO" />
    </logger>

    <springProfile name="dev,test">
        <root>
            <level value="DEBUG" />
            <appender-ref ref="stdout" />
        </root>
    </springProfile>
</configuration>

CronEntity.java

保存在數據庫中的表達式管理器.

package com.example.dynamicquartz.bean;

import java.io.Serializable;
import java.util.Date;

/**
 * created with IntelliJ IDEA.
 * packageName  : com.example.dynamicquartz.bean
 * author       : wujw
 * date         : 2018/9/9 16:23
 * version      : 1.0.0
 * description  : TODO
 */
public class CronEntity implements Serializable {
    private static final long serialVersionUID = -3406421161273529348L;

    private String id;

    private String userId; //用戶標識

    private String cron; //表達式

    private String quarzName; //任務名稱

    private String schedulerClass;//定時任務類

    private Date time;

    public String getId() {
        return id;
    }

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

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getCron() {
        return cron;
    }

    public void setCron(String cron) {
        this.cron = cron;
    }

    public String getQuarzName() {
        return quarzName;
    }

    public void setQuarzName(String quarzName) {
        this.quarzName = quarzName;
    }

    public String getSchedulerClass() {
        return schedulerClass;
    }

    public void setSchedulerClass(String schedulerClass) {
        this.schedulerClass = schedulerClass;
    }

    public Date getTime() {
        return time;
    }

    public void setTime(Date time) {
        this.time = time;
    }

    @Override
    public String toString() {
        return "CronEntity{" +
                "id=‘" + id + ‘\‘‘ +
                ", userId=‘" + userId + ‘\‘‘ +
                ", cron=‘" + cron + ‘\‘‘ +
                ", quarzName=‘" + quarzName + ‘\‘‘ +
                ", schedulerClass=‘" + schedulerClass + ‘\‘‘ +
                ", time=" + time +
                ‘}‘;
    }
}

CronMapper

package com.example.dynamicquartz.dao;

import com.example.dynamicquartz.bean.CronEntity;
import org.apache.ibatis.annotations.*;

import java.util.List;

/**
 * created with IntelliJ IDEA.
 * packageName  : com.example.dynamicquartz
 * author       : wujw
 * date         : 2018/9/9 20:14
 * version      : 1.0.0
 * description  : TODO
 */
@Mapper
public interface CronMapper{

    @Select("select * from cron_table where id = #{id}")
    @Results({
            @Result(property = "id",  column = "id"),
            @Result(property = "userId", column = "user_id"),
            @Result(property = "cron", column = "cron"),
            @Result(property = "quarzName", column = "quarz_name"),
            @Result(property = "schedulerClass", column = "scheduler_class"),
            @Result(property = "time", column = "time")
    })
    CronEntity load(String id);

    @Insert("insert into cron_table(id,userId,cron,quartzName,schedulerClass,time)" +
            "values(#{id},#{user_id},#{cron},#{quartz_name},#{scheduler_class},#      {time})")
    void insert(CronEntity cronEntity);

    @Select("select * from cron_table")
    @Results({
            @Result(property = "id",  column = "id"),
            @Result(property = "userId", column = "user_id"),
            @Result(property = "cron", column = "cron"),
            @Result(property = "quarzName", column = "quarz_name"),
            @Result(property = "schedulerClass", column = "scheduler_class"),
            @Result(property = "time", column = "time")
    })
    List<CronEntity> queryAll();

    @Update("update cron_table set cron=#{1} where id =#{0}")
    void updateCron(String id,String cron);
}

ICronService

package com.example.dynamicquartz.serivce;

import com.example.dynamicquartz.bean.CronEntity;

import java.util.List;

/**
 * created with IntelliJ IDEA.
 * packageName  : com.example.dynamicquartz
 * author       : wujw
 * date         : 2018/9/9 19:54
 * version      : 1.0.0
 * description  : TODO
 */
public interface ICronService{

    void sendEmail(String quartzName);

    void sendSms(String quartzName);

    CronEntity findByCronId(String id );

    void update(CronEntity cronEntity);

    List<CronEntity> findAll();
}

CronServiceImpl

package com.example.dynamicquartz.serivce;

import com.example.dynamicquartz.bean.CronEntity;
import com.example.dynamicquartz.dao.CronMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * created with IntelliJ IDEA.
 * packageName  : com.example.dynamicquartz.serivce
 * author       : wujw
 * date         : 2018/9/9 19:55
 * version      : 1.0.0
 * description  : TODO
 */
@Service
public class CronServiceImpl implements ICronService{

    @Autowired
    private CronMapper cronMapper;

    @Override
    public void sendEmail(String quartzName) {
        System.out.println(quartzName +" 正在發送郵件");
    }

    @Override
    public void sendSms(String quartzName) {
        System.out.println(quartzName +"正在發送短信");
    }

    @Override
    public CronEntity findByCronId(String id) {
        return this.cronMapper.load(id);
    }

    @Override
    public void update(CronEntity cronEntity) {
        this.cronMapper.insert(cronEntity);
    }

    @Override
    public List<CronEntity> findAll() {
        return this.cronMapper.queryAll();
    }
}

QuartzManager

package com.example.dynamicquartz.serivce;

import com.example.dynamicquartz.bean.CronEntity;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.util.Date;

/**
 * created with IntelliJ IDEA.
 * packageName  : com.example.dynamicquartz
 * author       : wujw
 * date         : 2018/9/9 19:31
 * version      : 1.0.0
 * description  : TODO
 */
@Configuration
public class QuartzManager {

    @Autowired
    private Scheduler scheduler;

    @Autowired
    private ICronService iCronService;

    public void start(String id) throws SchedulerException {
       CronEntity cronEntity = iCronService.findByCronId(id);
       if(cronEntity!= null){
   startJob(scheduler,cronEntity.getQuarzName(),cronEntity.getCron(),cronEntity.getSchedulerClass());
       }
    }
    
    private void startJob(Scheduler scheduler,String name,String cron,String className) throws SchedulerException {
        // 通過JobBuilder構建JobDetail實例,JobDetail規定只能是實現Job接口的實例
        // JobDetail 是具體Job實例
        Class<Job> jobClass = null;
        try {
           //實例化具體的Job任務
           jobClass = (Class<Job>) Class.forName(className);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(name, "group1").build();
        // 基於表達式構建觸發器
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(cron);
        // CronTrigger表達式觸發器 繼承於Trigger
        // TriggerBuilder 用於構建觸發器實例
        CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity(name, "group1")
                .withSchedule(cronScheduleBuilder).build();
        scheduler.scheduleJob(jobDetail, cronTrigger);
    }

    /**
     * 獲取Job信息
     *
     * @param name
     * @param group
     * @return
     * @throws SchedulerException
     */
    public String getJobInfo(String name, String group) throws SchedulerException {
        TriggerKey triggerKey = new TriggerKey(name, group);
        CronTrigger cronTrigger = (CronTrigger) scheduler.getTrigger(triggerKey);
        return String.format("time:%s,state:%s", cronTrigger.getCronExpression(),
                scheduler.getTriggerState(triggerKey).name());
    }

    /**
     * 修改某個任務的執行時間
     *
     * @param name
     * @param group
     * @param time
     * @return
     * @throws SchedulerException
     */
    public boolean modifyJob(String name, String group, String time) throws SchedulerException {
        Date date = null;
        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);
        }
        return date != null;
    }

    /**
     * 暫停所有任務
     *
     * @throws SchedulerException
     */
    public void pauseAllJob() throws SchedulerException {
        scheduler.pauseAll();
    }

    /**
     * 暫停某個任務
     *
     * @param name
     * @param group
     * @throws SchedulerException
     */
    public void pauseJob(String name, String group) throws SchedulerException {
        JobKey jobKey = new JobKey(name, group);
        JobDetail jobDetail = scheduler.getJobDetail(jobKey);
        if (jobDetail == null)
            return;
        scheduler.pauseJob(jobKey);
    }

    /**
     * 恢復所有任務
     *
     * @throws SchedulerException
     */
    public void resumeAllJob() throws SchedulerException {
        scheduler.resumeAll();
    }

    /**
     * 恢復某個任務
     *
     * @param name
     * @param group
     * @throws SchedulerException
     */
    public void resumeJob(String name, String group) throws SchedulerException {
        JobKey jobKey = new JobKey(name, group);
        JobDetail jobDetail = scheduler.getJobDetail(jobKey);
        if (jobDetail == null)
            return;
        scheduler.resumeJob(jobKey);
    }

    /**
     * 刪除某個任務
     *
     * @param name
     * @param group
     * @throws SchedulerException
     */
    public void deleteJob(String name, String group) throws SchedulerException {
        JobKey jobKey = new JobKey(name, group);
        JobDetail jobDetail = scheduler.getJobDetail(jobKey);
        if (jobDetail == null)
            return;
        scheduler.deleteJob(jobKey);
    }
}

創建兩個Task類,分別執行不同的任務

public class EmailTask implements Job {
    private Logger logger = LoggerFactory.getLogger(EmailTask.class);

    @Autowired
    private ICronService iCronService;


    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        logger.info("EmailTask task start execute.");
        //模擬任務執行
        iCronService.sendEmail(jobExecutionContext.getJobDetail().getKey().getName());
    }
}
public class SmsTask implements Job {
    private Logger logger = LoggerFactory.getLogger(SmsTask.class);

    @Autowired
    private ICronService iCronService;


    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        logger.info("SmsTask task start execute.");
        //模擬任務執行
        iCronService.sendSms(jobExecutionContext.getJobDetail().getKey().getName());
    }
}

SchedulerController

@RestController
@RequestMapping("/scheduler")
public class SchedulerController{
    @Autowired
    QuartzManager quartzManager;

    @RequestMapping(value = "/start", method = RequestMethod.GET)
     @ResponseBody
    public String start(@RequestParam(name = "id", defaultValue = "") String id) {
        try {
            quartzManager.start(id);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        return "啟動成功";
    }

}

cron_table.sql

CREATE TABLE `cron_table` (
  `id` varchar(11) collate utf8_bin NOT NULL,
  `user_id` varchar(11) collate utf8_bin default NULL,
  `cron` varchar(255) collate utf8_bin default NULL,
  `quarz_name` varchar(255) collate utf8_bin default NULL,
  `scheduler_class` varchar(255) collate utf8_bin default NULL,
  `time` datetime default NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

-- ----------------------------
-- Records of cron_table
-- ----------------------------
INSERT INTO `cron_table` VALUES (‘1‘, ‘AAA‘, ‘0/5 * * * * ?‘, ‘用戶AAA‘, ‘com.example.dynamicquartz.job.SmsTask‘, ‘2018-09-06 20:26:55‘);
INSERT INTO `cron_table` VALUES (‘2‘, ‘BBB‘, ‘0/2 * * * * ?‘, ‘用戶BBB‘, ‘com.example.dynamicquartz.job.EmailTask‘, ‘2018-09-09 21:02:08‘);

測試結果

http://localhost:8080/scheduler/start?id=1

http://localhost:8080/scheduler/start?id=2

2018-09-09 21:05:08,386 [http-nio-8080-exec-2] DEBUG com.example.dynamicquartz.dao.CronMapper.load - ==>  Preparing: select * from cron_table where id = ? 
2018-09-09 21:05:08,408 [http-nio-8080-exec-2] DEBUG com.example.dynamicquartz.dao.CronMapper.load - ==> Parameters: 1(String)
2018-09-09 21:05:08,427 [http-nio-8080-exec-2] DEBUG com.example.dynamicquartz.dao.CronMapper.load - <==      Total: 1
2018-09-09 21:05:10,036 [quartzScheduler_Worker-1] INFO  com.example.dynamicquartz.job.SmsTask - SmsTask task start execute.
用戶AAA正在發送短信
2018-09-09 21:05:11,581 [http-nio-8080-exec-1] DEBUG com.example.dynamicquartz.dao.CronMapper.load - ==>  Preparing: select * from cron_table where id = ? 
2018-09-09 21:05:11,582 [http-nio-8080-exec-1] DEBUG com.example.dynamicquartz.dao.CronMapper.load - ==> Parameters: 2(String)
2018-09-09 21:05:11,584 [http-nio-8080-exec-1] DEBUG com.example.dynamicquartz.dao.CronMapper.load - <==      Total: 1
2018-09-09 21:05:12,013 [quartzScheduler_Worker-2] INFO  com.example.dynamicquartz.job.EmailTask - EmailTask task start execute.
用戶BBB 正在發送郵件
2018-09-09 21:05:14,002 [quartzScheduler_Worker-3] INFO  com.example.dynamicquartz.job.EmailTask - EmailTask task start execute.
用戶BBB 正在發送郵件
2018-09-09 21:05:15,001 [quartzScheduler_Worker-4] INFO  com.example.dynamicquartz.job.SmsTask - SmsTask task start execute.
用戶AAA正在發送短信
2018-09-09 21:05:16,001 [quartzScheduler_Worker-5] INFO  com.example.dynamicquartz.job.EmailTask - EmailTask task start execute.
用戶BBB 正在發送郵件
2018-09-09 21:05:18,001 [quartzScheduler_Worker-6] INFO  com.example.dynamicquartz.job.EmailTask - EmailTask task start execute.
用戶BBB 正在發送郵件
2018-09-09 21:05:20,000 [quartzScheduler_Worker-7] INFO  com.example.dynamicquartz.job.SmsTask - SmsTask task start execute.
用戶AAA正在發送短信
2018-09-09 21:05:20,001 [quartzScheduler_Worker-8] INFO  com.example.dynamicquartz.job.EmailTask - EmailTask task start execute.
用戶BBB 正在發送郵件
2018-09-09 21:05:22,001 [quartzScheduler_Worker-9] INFO  com.example.dynamicquartz.job.EmailTask - EmailTask task start execute.
用戶BBB 正在發送郵件
2018-09-09 21:05:24,000 [quartzScheduler_Worker-10] INFO  com.example.dynamicquartz.job.EmailTask - EmailTask task start execute.
用戶BBB 正在發送郵件
2018-09-09 21:05:25,001 [quartzScheduler_Worker-1] INFO  com.example.dynamicquartz.job.SmsTask - SmsTask task start execute.
用戶AAA正在發送短信
2018-09-09 21:05:26,000 [quartzScheduler_Worker-2] INFO  com.example.dynamicquartz.job.EmailTask - EmailTask task start execute.
用戶BBB 正在發送郵件
2018-09-09 21:05:28,001 [quartzScheduler_Worker-3] INFO  com.example.dynamicquartz.job.EmailTask - EmailTask task start execute.

可以看出,AAA的間隔時間時5s,BBB的間隔時間時2s.

到這裏我們的測試已經一本完成了,接下來就是針對任務的更新,停止和啟動了,只需要調用QuartzManager對應的方法即可,必要時更新一下數據庫就好啦。

Quartz+Spring Boot實現動態管理定時任務