springboot整合quartz定時任務框架的完整步驟

Spring整合Quartz

  1. 添加maven配置。
  2. 相關配置文件(不管是properties 還是yml。采用JDBC存儲)。
  3. 創建quartz使用的數據表。
  4. 業務邏輯層中使用。
  5. 數據表
  6. 具體使用

pom文件

如下所示:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-quartz</artifactId>
        </dependency>

對應的properties 文件

放在resource目錄下

# ===========================================================================
# Configure Main Scheduler Properties 調度器屬性
# ===========================================================================
#調度標識名 集群中每一個實例都必須使用相同的名稱
org.quartz.scheduler.instanceName = DefaultQuartzScheduler
#ID設置為自動獲取 每一個必須不同
org.quartz.scheduler.instanceId = AUTO
#============================================================================
# Configure ThreadPool
#============================================================================
#線程池的實現類(一般使用SimpleThreadPool即可滿足幾乎所有用戶的需求)
org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool
#指定線程數,至少為1(無默認值)(一般設置為1-100直接的整數合適)
org.quartz.threadPool.threadCount = 25
#設置線程的優先級(最大為java.lang.Thread.MAX_PRIORITY 10,最小為Thread.MIN_PRIORITY 1,默認為5)
org.quartz.threadPool.threadPriority = 5
#============================================================================
# Configure JobStore
#============================================================================
# 觸發失敗閾值,未超過觸發時間60s則直接觸發,若超過則失火,log信息Handling 1 trigger(s) that missed their scheduled fire-time.
org.quartz.jobStore.misfireThreshold = 60000
#數據保存方式為數據庫持久化
org.quartz.jobStore.class = org.quartz.impl.jdbcjobstore.JobStoreTX
#數據庫代理類,一般org.quartz.impl.jdbcjobstore.StdJDBCDelegate可以滿足大部分數據庫
org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.StdJDBCDelegate
#JobDataMaps是否都為String類型
org.quartz.jobStore.useProperties = false
#表的前綴,默認QRTZ_
org.quartz.jobStore.tablePrefix = QRTZ_
#是否加入集群
org.quartz.jobStore.isClustered = true
#調度實例失效的檢查時間間隔
org.quartz.jobStore.clusterCheckinInterval = 20000

配置類

package com.anjie.manage.quartz;

import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.scheduling.quartz.SpringBeanJobFactory;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;
import java.io.IOException;

@Configuration
public class QuartzConfig {
    @Autowired
    private DataSource dataSource;

    @Autowired
    private PlatformTransactionManager txManager;

    @Bean(name = "quartzScheduler")
    public SchedulerFactoryBean quartzScheduler() throws IOException {
        //創建SchedulerFactoryBean
        SchedulerFactoryBean factory = new SchedulerFactoryBean();
        //設置調度器自動運行
        factory.setAutoStartup(true);
        //設置配置文件位置
        factory.setConfigLocation(new ClassPathResource("/quartz.properties"));
        //設置job工廠,使job可以自動註入
        SpringBeanJobFactory jobFactory = new SpringBeanJobFactory();
        factory.setJobFactory(jobFactory);
        //設置數據源
        factory.setDataSource(dataSource);
        //設置事務
        factory.setTransactionManager(txManager);
        //設置重寫已存在的Job
        factory.setOverwriteExistingJobs(true);
        return factory;
    }

    @Bean(name = "scheduler")
    public Scheduler scheduler() throws IOException {
        return quartzScheduler().getScheduler();
    }
}

自定義任務類:ScheduledTask

package com.anjie.manage.quartz;

import com.anjie.auth.common.exception.BadConfigurationException;
import com.anjie.manage.common.SpringContextUtil;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.springframework.context.ApplicationContext;

import java.lang.reflect.Method;

@Slf4j
@Setter
public class ScheduledTask implements Job {

    private Integer id;

    private String params;

    private String serviceBeanName;

    private String methodName;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) {
        try {
            //使用反射執行spring中的任務
            ApplicationContext wac = SpringContextUtil.getApplicationContext();
            Class<?> serviceBean = wac.getBean(serviceBeanName).getClass();
            if (StringUtils.isNotEmpty(params)){
                Method method = serviceBean.getDeclaredMethod(methodName,String.class);
                method.invoke(wac.getBean(serviceBean),params);
            }else {
                Method method = serviceBean.getDeclaredMethod(methodName,null);
                method.invoke(wac.getBean(serviceBean),null);
            }
        }catch (Exception e){
            throw new BadConfigurationException("任務執行失敗");
        }

    }
}

獲取spring中bean的工具類:SpringContextUtil

package com.anjie.manage.common;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class SpringContextUtil implements ApplicationContextAware {
    private static ApplicationContext applicationContext = null;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtil.applicationContext = applicationContext;
    }

    /**
     * 獲取applicationContext
     * @return
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }


}

定時任務服務接口:QuartzService

package com.anjie.manage.quartz.service;

import com.anjie.manage.quartz.entity.po.QuartzTask;

import java.util.List;

public interface QuartzService {
    void initAllTask(List<QuartzTask> scheduledTaskBeanList) throws Exception;

    void addJob(QuartzTask scheduledTask);

    void updateJob(QuartzTask quartzTask);

    void deleteJob(QuartzTask quartzTask);

    void runJobOnce(QuartzTask quartzTask);
}

QuartzService實現類:QuartzServiceImpl

package com.anjie.manage.quartz.service.impl;

import com.anjie.manage.quartz.entity.po.QuartzTask;
import com.anjie.manage.quartz.ScheduledTask;
import com.anjie.manage.quartz.service.QuartzService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

@Service
@Slf4j
public class QuartzServiceImpl implements QuartzService {
    @Autowired
    private Scheduler scheduler;

    @Override
    public void initAllTask(List<QuartzTask> quartzTaskList) throws Exception {
        log.info("程序啟動 ==> 初始化所有任務開始 !");
        if (CollectionUtils.isEmpty(quartzTaskList)) {
            scheduler.shutdown();
            return;
        }
        for (QuartzTask quartzTask : quartzTaskList) {
            //判斷是否啟動狀態
            if (quartzTask.getStatus()) {
                this.addJob(quartzTask);
            }
        }
        log.info("程序啟動 ==> 初始化所有任務結束 !");
    }

    @Override
    public void addJob(QuartzTask quartzTask) {
        String taskName = quartzTask.getTaskName();
        String groupName = quartzTask.getGroupName();
        String cron = quartzTask.getCron();
        TriggerKey triggerKey = TriggerKey.triggerKey(taskName, groupName);
        try {
            boolean result = scheduler.checkExists(triggerKey);
            //job已存在,直接返回
            log.info("checkExists quartTask = {} , result = {}", quartzTask, result);
            if (result) {
                return;
            }
            Job job = new ScheduledTask();
            //構建job信息
            JobDetail jobDetail = JobBuilder.newJob(job.getClass()).withIdentity(taskName, groupName).build();
            //表達式調度構建器(即任務執行的時間)
            /*使用withMisfireHandlingInstructionDoNothing是因為重啟項目時之前添加的job都算失火
            ,默認配置withMisfireHandlingInstructionFireAndProceed失火後會立即執行一遍,
            而withMisfireHandlingInstructionDoNothing失火後不會立即執行,而是按照下一個cron執行
            */
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cron).withMisfireHandlingInstructionDoNothing();
            //按新的cronExpression表達式構建一個新的trigger
            CronTrigger trigger = TriggerBuilder.newTrigger().startNow().withIdentity(taskName, groupName).withSchedule(scheduleBuilder).build();

            String[] serviceBean = quartzTask.getJobClass().split("\\.");
            //獲得JobDataMap,寫入數據
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("id", quartzTask.getId());
            paramMap.put("params", quartzTask.getParams());
            paramMap.put("methodName",serviceBean[1]);
            paramMap.put("serviceBeanName",serviceBean[0]);
            trigger.getJobDataMap().putAll(paramMap);
            scheduler.scheduleJob(jobDetail, trigger);
            log.info("addJob quartTask = {} is success", quartzTask);
        } catch (Exception e) {
            log.error("addJob quartTask = {} is fail, msg = {}", quartzTask, e);
        }
    }

    @Override
    public void updateJob(QuartzTask quartzTask) {
        String taskName = quartzTask.getTaskName();
        String groupName = quartzTask.getGroupName();
        String cron = quartzTask.getCron();
        TriggerKey triggerKey = TriggerKey.triggerKey(taskName, groupName);
        try {
            CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
            if (cron != null) {
                // 表達式調度構建器
                CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cron).withMisfireHandlingInstructionDoNothing();
                // 按新的cronExpression表達式重新構建trigger
                trigger = trigger.getTriggerBuilder().startNow().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
            }

            String[] serviceBean = quartzTask.getJobClass().split("\\.");
            //獲得JobDataMap,寫入數據
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("id", quartzTask.getId());
            paramMap.put("params", quartzTask.getParams());
            paramMap.put("serviceBeanName",serviceBean[0]);
            paramMap.put("methodName",serviceBean[1]);
            trigger.getJobDataMap().putAll(paramMap);
            // 按新的trigger重新設置job執行
            scheduler.rescheduleJob(triggerKey, trigger);
            log.info("updateJob quartTask = {} is success", quartzTask);
        } catch (SchedulerException e) {
            log.error("updateJob quartTask = {} is fail, msg = {}", quartzTask, e);
        }
    }

    @Override
    public void deleteJob(QuartzTask quartzTask) {
        String taskName = quartzTask.getTaskName();
        String groupName = quartzTask.getGroupName();
        try {
            scheduler.pauseTrigger(TriggerKey.triggerKey(taskName, groupName));
            scheduler.unscheduleJob(TriggerKey.triggerKey(taskName, groupName));
            scheduler.deleteJob(JobKey.jobKey(taskName, groupName));
            log.info("deleteJob quartTask = {} is success", quartzTask);
        } catch (SchedulerException e) {
            log.error("deleteJob quartTask = {} is fail, msg = {}", quartzTask, e);
        }
    }

    @Override
    public void runJobOnce(QuartzTask quartzTask){
        String taskName = UUID.randomUUID().toString();
        String groupName = UUID.randomUUID().toString();
        try {
//            Class<?> aClass = Class.forName(quartzTask.getJobClass());
            Job job = new ScheduledTask();
            //構建job信息
            JobDetail jobDetail = JobBuilder.newJob(job.getClass()).withIdentity(taskName, groupName).build();

            SimpleTrigger simpleTrigger = TriggerBuilder.newTrigger()
                    .withIdentity(taskName, groupName)
                    .startAt(new Date())
                    .withSchedule(SimpleScheduleBuilder.simpleSchedule()
                            .withIntervalInSeconds(1)
                            .withRepeatCount(0))//重復執行的次數,因為加入任務的時候馬上執行瞭,所以不需要重復,否則會多一次。
                    .build();
            String[] serviceBean = quartzTask.getJobClass().split("\\.");
            //獲得JobDataMap,寫入數據
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("id", quartzTask.getId());
            paramMap.put("params", quartzTask.getParams());
            paramMap.put("serviceBeanName",serviceBean[0]);
            paramMap.put("methodName",serviceBean[1]);
            simpleTrigger.getJobDataMap().putAll(paramMap);
            scheduler.scheduleJob(jobDetail, simpleTrigger);
        }catch (Exception e){
            log.error("run job quartTask = {} is fail, msg = {}", quartzTask, e);
        }
    }
}

ScheduledTaskRunner類

項目啟動後獲取數據庫中的定時任務列表,初始化定時任務

package com.anjie.manage.quartz;

import com.anjie.manage.quartz.entity.po.QuartzTask;
import com.anjie.manage.quartz.service.QuartzService;
import com.anjie.manage.quartz.service.QuartzTaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Order(value = 1)
@Slf4j
public class ScheduledTaskRunner implements ApplicationRunner {
    @Autowired
    private QuartzTaskService quartzTaskService;

    @Autowired
    private QuartzService quartzService;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info(" >>>>>> 項目啟動完畢, 開啟 => 需要自啟的任務 開始!");
        List<QuartzTask> activatedTaskList = quartzTaskService.list();
        quartzService.initAllTask(activatedTaskList);
        log.info(" >>>>>> 項目啟動完畢, 開啟 => 需要自啟的任務 結束!");
    }
}

任務實體類:QuartzTask

映射數據庫自定義任務表

package com.anjie.manage.quartz.entity.po;

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

@Data
@TableName(value = "quartz_task")
public class QuartzTask {
    /**
     * 主鍵
     */
    @TableId(type = IdType.AUTO)
    private Integer id;

    /**
     * 任務名稱
     */
    private String taskName;

    /**
     * group名稱
     */
    private String groupName;

    /**
     * job所在類
     */
    private String jobClass;

    /**
     * 參數
     */
    private String params;

    /**
     * cron表達式
     */
    private String cron;

    /**
     * 狀態
     */
    private Boolean status;

    /**
     * 任務描述
     */
    private String des;
}

任務dao層,我是用的是mybatis-plus

package com.anjie.manage.quartz.dao;

import com.anjie.manage.quartz.entity.po.QuartzTask;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

@Repository
@Mapper
public interface QuartzTaskDao extends BaseMapper<QuartzTask> {
}

任務service層

package com.anjie.manage.quartz.service;


import com.anjie.manage.quartz.entity.po.QuartzTask;
import com.baomidou.mybatisplus.extension.service.IService;

public interface QuartzTaskService extends IService<QuartzTask> {
}

service實現類

package com.anjie.manage.quartz.service.impl;

import com.anjie.manage.quartz.entity.po.QuartzTask;
import com.anjie.manage.quartz.dao.QuartzTaskDao;
import com.anjie.manage.quartz.service.QuartzTaskService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

@Service
public class QuartzTaskServiceImpl
        extends ServiceImpl<QuartzTaskDao, QuartzTask>
        implements QuartzTaskService
{

}

任務controller

package com.anjie.manage.quartz.controller;

import com.anjie.manage.common.ResponseMessage;
import com.anjie.manage.quartz.service.QuartzService;
import com.anjie.manage.quartz.entity.po.QuartzTask;
import com.anjie.manage.quartz.service.QuartzTaskService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@Slf4j
@RequestMapping("/quartz")
public class JobController {
    @Autowired
    private QuartzService quartzService;

    @Autowired
    private QuartzTaskService quartzTaskService;

    @PostMapping("/job")
    public ResponseMessage addJob(@RequestBody QuartzTask quartzTask){
        QueryWrapper<QuartzTask> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("task_name",quartzTask.getTaskName());
        QuartzTask queryResult = quartzTaskService.getOne(queryWrapper);
        if (queryResult != null){
            return ResponseMessage.fail("任務名稱已存在!");
        }
        quartzTaskService.save(quartzTask);
        return ResponseMessage.ok("操作成功!");
    }

    @PutMapping("/job")
    public ResponseMessage updateJob(@RequestBody QuartzTask quartzTask){
        //判斷任務是否啟用
        Boolean status = quartzTaskService.getById(quartzTask.getId()).getStatus();
        if (status){
            return ResponseMessage.fail("任務正在運行中,請暫停後修改!");
        }
        //判斷任務名稱是否重名
        QueryWrapper<QuartzTask> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("task_name",quartzTask.getTaskName());
        QuartzTask queryResult = quartzTaskService.getOne(queryWrapper);
        if (queryResult != null &&!queryResult.getId().equals(quartzTask.getId())){
            return ResponseMessage.fail("任務名稱已存在!");
        }
        quartzTaskService.updateById(quartzTask);
        return ResponseMessage.ok("操作成功!");
    }

    @DeleteMapping("/job/{id}")
    public ResponseMessage deleteJob(@PathVariable Integer id){
        //判斷任務是否啟用
        Boolean status = quartzTaskService.getById(id).getStatus();
        if (status){
            return ResponseMessage.fail("任務正在運行中,請暫停後刪除!");
        }
        quartzTaskService.removeById(id);
        return ResponseMessage.ok("操作成功!");
    }

    @GetMapping("/job")
    public ResponseMessage getJobPage(Page<QuartzTask> page,QuartzTask params){
        QueryWrapper<QuartzTask> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(params.getDes())){
            queryWrapper.like("des",params.getDes());
        }
        if (StringUtils.isNotEmpty(params.getTaskName())){
            queryWrapper.like("task_name",params.getTaskName());
        }
        if (StringUtils.isNotEmpty(params.getGroupName())){
            queryWrapper.like("group_name",params.getGroupName());
        }
        if (params.getStatus() != null){
            queryWrapper.eq("status",params.getStatus());
        }
        queryWrapper.orderByDesc("id");
        IPage<QuartzTask> result = quartzTaskService.page(page,queryWrapper);
        return ResponseMessage.ok("操作成功",result);
    }
    /**
     * 修改任務的cron
     *
     * @return
     */
//    @RequestMapping(value = "/updateJobCron",method = RequestMethod.PUT)
//    public Object updateJobCron(Integer id, String cron) {
//        QuartzTask quartzTask = quartzTaskService.getById(id);
//        Map<String, String> resultMap = new HashMap<>();
//        //如果存在quartzTask對象
//        if (quartzTask != null) {
//            //修改任務的cron
//            quartzTask.setCron(cron);
//            //更新quart_task
//            quartzTaskService.updateById(quartzTask);
//            //如果啟用狀態則修改當前已持久化的job
//            if (quartzTask.getStatus()) {
//                quartzService.updateJob(quartzTask);
//            }
//            resultMap.put("status", "0");
//            resultMap.put("msg", "修改cron成功");
//            return resultMap;
//        }
//        //不存在quartzTask對象
//        resultMap.put("status", "1");
//        resultMap.put("msg", "修改cron失敗");
//        return resultMap;
//    }

    /**
     * 是否啟用接口
     *
     * @return
     */
    @PutMapping(value = "/jobStatus")
    public ResponseMessage updateJobStatus(@RequestBody QuartzTask params) {
        QuartzTask quartzTask = quartzTaskService.getById(params.getId());
        if (quartzTask != null) {
            //修改任務的啟用狀態
            quartzTask.setStatus(params.getStatus());
            //更新quart_task
            boolean updateResult = quartzTaskService.updateById(quartzTask);
            //根據status判斷是新增job還是刪除job
            if (params.getStatus() && updateResult) {
                quartzService.addJob(quartzTask);
            } else if (updateResult){
                quartzService.deleteJob(quartzTask);
            }
            return ResponseMessage.ok("修改狀態成功");
        }
        return ResponseMessage.fail("修改狀態失敗");
    }

    /**
     * 啟用一次任務
     * @author  **
     * @param id 任務id
     * @return java.lang.Object
     */
    @PostMapping("/runJob/{id}")
    public ResponseMessage runJobOnce(@PathVariable Integer id){
        QuartzTask quartzTask = quartzTaskService.getById(id);
        if (quartzTask != null) {
            quartzService.runJobOnce(quartzTask);
            return ResponseMessage.ok("任務執行成功");
        }
        return ResponseMessage.fail("任務執行失敗");
    }
}

到目前位置就對quartz框架整合完成,這裡附上具體使用到的數據表

數據表

-- ----------------------------
-- Table structure for QRTZ_BLOB_TRIGGERS
-- ----------------------------
DROP TABLE IF EXISTS `QRTZ_BLOB_TRIGGERS`;
CREATE TABLE `QRTZ_BLOB_TRIGGERS`  (
  `SCHED_NAME` varchar(120) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
  `TRIGGER_NAME` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
  `TRIGGER_GROUP` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
  `BLOB_DATA` blob NULL,
  PRIMARY KEY (`SCHED_NAME`, `TRIGGER_NAME`, `TRIGGER_GROUP`) USING BTREE,
  INDEX `SCHED_NAME`(`SCHED_NAME`, `TRIGGER_NAME`, `TRIGGER_GROUP`) USING BTREE,
  CONSTRAINT `QRTZ_BLOB_TRIGGERS_ibfk_1` FOREIGN KEY (`SCHED_NAME`, `TRIGGER_NAME`, `TRIGGER_GROUP`) REFERENCES `QRTZ_TRIGGERS` (`SCHED_NAME`, `TRIGGER_NAME`, `TRIGGER_GROUP`) ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Table structure for QRTZ_CALENDARS
-- ----------------------------
DROP TABLE IF EXISTS `QRTZ_CALENDARS`;
CREATE TABLE `QRTZ_CALENDARS`  (
  `SCHED_NAME` varchar(120) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
  `CALENDAR_NAME` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
  `CALENDAR` blob NOT NULL,
  PRIMARY KEY (`SCHED_NAME`, `CALENDAR_NAME`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Table structure for QRTZ_CRON_TRIGGERS
-- ----------------------------
DROP TABLE IF EXISTS `QRTZ_CRON_TRIGGERS`;
CREATE TABLE `QRTZ_CRON_TRIGGERS`  (
  `SCHED_NAME` varchar(120) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
  `TRIGGER_NAME` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
  `TRIGGER_GROUP` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
  `CRON_EXPRESSION` varchar(120) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
  `TIME_ZONE_ID` varchar(80) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL,
  PRIMARY KEY (`SCHED_NAME`, `TRIGGER_NAME`, `TRIGGER_GROUP`) USING BTREE,
  CONSTRAINT `QRTZ_CRON_TRIGGERS_ibfk_1` FOREIGN KEY (`SCHED_NAME`, `TRIGGER_NAME`, `TRIGGER_GROUP`) REFERENCES `QRTZ_TRIGGERS` (`SCHED_NAME`, `TRIGGER_NAME`, `TRIGGER_GROUP`) ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Table structure for QRTZ_FIRED_TRIGGERS
-- ----------------------------
DROP TABLE IF EXISTS `QRTZ_FIRED_TRIGGERS`;
CREATE TABLE `QRTZ_FIRED_TRIGGERS`  (
  `SCHED_NAME` varchar(120) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
  `ENTRY_ID` varchar(95) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
  `TRIGGER_NAME` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
  `TRIGGER_GROUP` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
  `INSTANCE_NAME` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
  `FIRED_TIME` bigint(13) NOT NULL,
  `SCHED_TIME` bigint(13) NOT NULL,
  `PRIORITY` int(11) NOT NULL,
  `STATE` varchar(16) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
  `JOB_NAME` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL,
  `JOB_GROUP` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL,
  `IS_NONCONCURRENT` varchar(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL,
  `REQUESTS_RECOVERY` varchar(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL,
  PRIMARY KEY (`SCHED_NAME`, `ENTRY_ID`) USING BTREE,
  INDEX `IDX_QRTZ_FT_TRIG_INST_NAME`(`SCHED_NAME`, `INSTANCE_NAME`) USING BTREE,
  INDEX `IDX_QRTZ_FT_INST_JOB_REQ_RCVRY`(`SCHED_NAME`, `INSTANCE_NAME`, `REQUESTS_RECOVERY`) USING BTREE,
  INDEX `IDX_QRTZ_FT_J_G`(`SCHED_NAME`, `JOB_NAME`, `JOB_GROUP`) USING BTREE,
  INDEX `IDX_QRTZ_FT_JG`(`SCHED_NAME`, `JOB_GROUP`) USING BTREE,
  INDEX `IDX_QRTZ_FT_T_G`(`SCHED_NAME`, `TRIGGER_NAME`, `TRIGGER_GROUP`) USING BTREE,
  INDEX `IDX_QRTZ_FT_TG`(`SCHED_NAME`, `TRIGGER_GROUP`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Table structure for QRTZ_JOB_DETAILS
-- ----------------------------
DROP TABLE IF EXISTS `QRTZ_JOB_DETAILS`;
CREATE TABLE `QRTZ_JOB_DETAILS`  (
  `SCHED_NAME` varchar(120) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
  `JOB_NAME` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
  `JOB_GROUP` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
  `DESCRIPTION` varchar(250) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL,
  `JOB_CLASS_NAME` varchar(250) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
  `IS_DURABLE` varchar(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
  `IS_NONCONCURRENT` varchar(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
  `IS_UPDATE_DATA` varchar(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
  `REQUESTS_RECOVERY` varchar(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
  `JOB_DATA` blob NULL,
  PRIMARY KEY (`SCHED_NAME`, `JOB_NAME`, `JOB_GROUP`) USING BTREE,
  INDEX `IDX_QRTZ_J_REQ_RECOVERY`(`SCHED_NAME`, `REQUESTS_RECOVERY`) USING BTREE,
  INDEX `IDX_QRTZ_J_GRP`(`SCHED_NAME`, `JOB_GROUP`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Table structure for QRTZ_LOCKS
-- ----------------------------
DROP TABLE IF EXISTS `QRTZ_LOCKS`;
CREATE TABLE `QRTZ_LOCKS`  (
  `SCHED_NAME` varchar(120) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
  `LOCK_NAME` varchar(40) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
  PRIMARY KEY (`SCHED_NAME`, `LOCK_NAME`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Table structure for QRTZ_PAUSED_TRIGGER_GRPS
-- ----------------------------
DROP TABLE IF EXISTS `QRTZ_PAUSED_TRIGGER_GRPS`;
CREATE TABLE `QRTZ_PAUSED_TRIGGER_GRPS`  (
  `SCHED_NAME` varchar(120) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
  `TRIGGER_GROUP` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
  PRIMARY KEY (`SCHED_NAME`, `TRIGGER_GROUP`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Table structure for QRTZ_SCHEDULER_STATE
-- ----------------------------
DROP TABLE IF EXISTS `QRTZ_SCHEDULER_STATE`;
CREATE TABLE `QRTZ_SCHEDULER_STATE`  (
  `SCHED_NAME` varchar(120) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
  `INSTANCE_NAME` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
  `LAST_CHECKIN_TIME` bigint(13) NOT NULL,
  `CHECKIN_INTERVAL` bigint(13) NOT NULL,
  PRIMARY KEY (`SCHED_NAME`, `INSTANCE_NAME`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Table structure for QRTZ_SIMPLE_TRIGGERS
-- ----------------------------
DROP TABLE IF EXISTS `QRTZ_SIMPLE_TRIGGERS`;
CREATE TABLE `QRTZ_SIMPLE_TRIGGERS`  (
  `SCHED_NAME` varchar(120) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
  `TRIGGER_NAME` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
  `TRIGGER_GROUP` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
  `REPEAT_COUNT` bigint(7) NOT NULL,
  `REPEAT_INTERVAL` bigint(12) NOT NULL,
  `TIMES_TRIGGERED` bigint(10) NOT NULL,
  PRIMARY KEY (`SCHED_NAME`, `TRIGGER_NAME`, `TRIGGER_GROUP`) USING BTREE,
  CONSTRAINT `QRTZ_SIMPLE_TRIGGERS_ibfk_1` FOREIGN KEY (`SCHED_NAME`, `TRIGGER_NAME`, `TRIGGER_GROUP`) REFERENCES `QRTZ_TRIGGERS` (`SCHED_NAME`, `TRIGGER_NAME`, `TRIGGER_GROUP`) ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Table structure for QRTZ_SIMPROP_TRIGGERS
-- ----------------------------
DROP TABLE IF EXISTS `QRTZ_SIMPROP_TRIGGERS`;
CREATE TABLE `QRTZ_SIMPROP_TRIGGERS`  (
  `SCHED_NAME` varchar(120) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
  `TRIGGER_NAME` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
  `TRIGGER_GROUP` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
  `STR_PROP_1` varchar(512) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL,
  `STR_PROP_2` varchar(512) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL,
  `STR_PROP_3` varchar(512) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL,
  `INT_PROP_1` int(11) NULL DEFAULT NULL,
  `INT_PROP_2` int(11) NULL DEFAULT NULL,
  `LONG_PROP_1` bigint(20) NULL DEFAULT NULL,
  `LONG_PROP_2` bigint(20) NULL DEFAULT NULL,
  `DEC_PROP_1` decimal(13, 4) NULL DEFAULT NULL,
  `DEC_PROP_2` decimal(13, 4) NULL DEFAULT NULL,
  `BOOL_PROP_1` varchar(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL,
  `BOOL_PROP_2` varchar(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL,
  PRIMARY KEY (`SCHED_NAME`, `TRIGGER_NAME`, `TRIGGER_GROUP`) USING BTREE,
  CONSTRAINT `QRTZ_SIMPROP_TRIGGERS_ibfk_1` FOREIGN KEY (`SCHED_NAME`, `TRIGGER_NAME`, `TRIGGER_GROUP`) REFERENCES `QRTZ_TRIGGERS` (`SCHED_NAME`, `TRIGGER_NAME`, `TRIGGER_GROUP`) ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Table structure for QRTZ_TRIGGERS
-- ----------------------------
DROP TABLE IF EXISTS `QRTZ_TRIGGERS`;
CREATE TABLE `QRTZ_TRIGGERS`  (
  `SCHED_NAME` varchar(120) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
  `TRIGGER_NAME` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
  `TRIGGER_GROUP` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
  `JOB_NAME` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
  `JOB_GROUP` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
  `DESCRIPTION` varchar(250) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL,
  `NEXT_FIRE_TIME` bigint(13) NULL DEFAULT NULL,
  `PREV_FIRE_TIME` bigint(13) NULL DEFAULT NULL,
  `PRIORITY` int(11) NULL DEFAULT NULL,
  `TRIGGER_STATE` varchar(16) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
  `TRIGGER_TYPE` varchar(8) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
  `START_TIME` bigint(13) NOT NULL,
  `END_TIME` bigint(13) NULL DEFAULT NULL,
  `CALENDAR_NAME` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL,
  `MISFIRE_INSTR` smallint(2) NULL DEFAULT NULL,
  `JOB_DATA` blob NULL,
  PRIMARY KEY (`SCHED_NAME`, `TRIGGER_NAME`, `TRIGGER_GROUP`) USING BTREE,
  INDEX `IDX_QRTZ_T_J`(`SCHED_NAME`, `JOB_NAME`, `JOB_GROUP`) USING BTREE,
  INDEX `IDX_QRTZ_T_JG`(`SCHED_NAME`, `JOB_GROUP`) USING BTREE,
  INDEX `IDX_QRTZ_T_C`(`SCHED_NAME`, `CALENDAR_NAME`) USING BTREE,
  INDEX `IDX_QRTZ_T_G`(`SCHED_NAME`, `TRIGGER_GROUP`) USING BTREE,
  INDEX `IDX_QRTZ_T_STATE`(`SCHED_NAME`, `TRIGGER_STATE`) USING BTREE,
  INDEX `IDX_QRTZ_T_N_STATE`(`SCHED_NAME`, `TRIGGER_NAME`, `TRIGGER_GROUP`, `TRIGGER_STATE`) USING BTREE,
  INDEX `IDX_QRTZ_T_N_G_STATE`(`SCHED_NAME`, `TRIGGER_GROUP`, `TRIGGER_STATE`) USING BTREE,
  INDEX `IDX_QRTZ_T_NEXT_FIRE_TIME`(`SCHED_NAME`, `NEXT_FIRE_TIME`) USING BTREE,
  INDEX `IDX_QRTZ_T_NFT_ST`(`SCHED_NAME`, `TRIGGER_STATE`, `NEXT_FIRE_TIME`) USING BTREE,
  INDEX `IDX_QRTZ_T_NFT_MISFIRE`(`SCHED_NAME`, `MISFIRE_INSTR`, `NEXT_FIRE_TIME`) USING BTREE,
  INDEX `IDX_QRTZ_T_NFT_ST_MISFIRE`(`SCHED_NAME`, `MISFIRE_INSTR`, `NEXT_FIRE_TIME`, `TRIGGER_STATE`) USING BTREE,
  INDEX `IDX_QRTZ_T_NFT_ST_MISFIRE_GRP`(`SCHED_NAME`, `MISFIRE_INSTR`, `NEXT_FIRE_TIME`, `TRIGGER_GROUP`, `TRIGGER_STATE`) USING BTREE,
  CONSTRAINT `QRTZ_TRIGGERS_ibfk_1` FOREIGN KEY (`SCHED_NAME`, `JOB_NAME`, `JOB_GROUP`) REFERENCES `QRTZ_JOB_DETAILS` (`SCHED_NAME`, `JOB_NAME`, `JOB_GROUP`) ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Table structure for quartz_task
-- ----------------------------
DROP TABLE IF EXISTS `quartz_task`;
CREATE TABLE `quartz_task`  (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主鍵',
  `task_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '任務名稱',
  `group_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT 'group名稱',
  `job_class` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT 'job所在類',
  `params` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '參數',
  `cron` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT 'cron表達式',
  `status` tinyint(1) NULL DEFAULT 0 COMMENT '狀態',
  `des` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '描述',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 16 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci ROW_FORMAT = Dynamic;

具體使用

1、新建具體需要執行任務

package com.anjie.manage.quartz;

import com.anjie.manage.quartz.service.QuartzTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class Task01 {
    @Autowired
    private QuartzTaskService quartzTaskService;

    public void test(String param){
        quartzTaskService.list();
        System.out.println("test01被執行(任務示例)"+param);
    }
}

2、配置定時任務

註意:

1.這裡的任務路徑是需要執行的類中的方法路徑,采用bean的名稱 + 方法名(例:task01.test),名稱首字母小寫,不然會找不到bean,也可以自己給需要執行的任務類bean起名

2.參數是字符串,可以自己寫json字符串,是否傳參與方法中保持一致,方法中有形參,這裡就必傳,方法沒有形參,這裡就不傳,不然任務會執行失敗

具體效果

總結

到此這篇關於springboot整合quartz定時任務框架的文章就介紹到這瞭,更多相關springboot整合quartz定時任務內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: