亲宝软件园·资讯

展开

springboot整合quartz定时任务

蔚蓝色的咸鱼 人气:0

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字符串,是否传参与方法中保持一致,方法中有形参,这里就必传,方法没有形参,这里就不传,不然任务会执行失败

具体效果

总结

加载全部内容

相关教程
猜你喜欢
用户评论