Quartz定时器实现

2 篇文章 0 订阅
1 篇文章 0 订阅

定时任务的执行有多种方法,其中常使用的定时器有JDK Timer、Spring Task、Quartz等三种。JDK自带的定时器Timer使用灵活,配置简单,适用于一些中小项目;Spring Task配置较为简单轻量,需要Spring框架支持;Quartz的功能强大,配置也比较复杂,适合大型、多定时任务的项目使用。可以参考下面几个博主的文章

Java定时器(Timer)_罗汉爷的博客-CSDN博客_java timer

spring-boot定时器_Leo187的博客-CSDN博客

定时任务框架Quartz-(一)Quartz入门与Demo搭建_是Guava不是瓜娃的博客-CSDN博客_quartz

在这里我记录一次自己springboot项目中使用自定义注解加quartz实现自定义配置的定时方案。

pom.xml

       <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.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
            <version>2.2.1</version>
            <!-- Quartz默认需要slf4j支持。springboot中,提供了更高版本的slf4j -->
            <exclusions>
                <exclusion>
                    <artifactId>slf4j-api</artifactId>
                    <groupId>org.slf4j</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>5.3.9</version>
        </dependency>

配置文件application-dev.yml:

#定时任务配置
scheduler:
  enable: true #默认false,不启用

任务管理类

package com.rainnie.demo.config;

import com.rainnie.demo.service.JobManageService;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @PackageName: com.rainnie.demo.config
 * @ClaseName: SchedulerManager
 * @Description: SchedulerManager
 * @Author: rainnie
 * @Date: 2022/3/25 9:36
 * @params *@params 定时任务管理类$
 */
@Component
public class SchedulerManager implements ApplicationRunner {
    private Logger logger = LoggerFactory.getLogger(SchedulerManager.class);

    @Value("${scheduler.enable:false}")
    private Boolean enable;

    @Autowired(required = false)
    private SchedulerFactoryBean schedulerFactoryBean;

    private static final String JOB_NAME = "_JOB_NAME";
    private static final String TRIGGER_NAME = "_TRIGGER_NAME";
    private static final String GROUP = "_GROUP";

    private Scheduler scheduler = null;

    @Autowired(required = false)
    private JobManageService jobManageService;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        scheduler = schedulerFactoryBean.getScheduler();
        try {
            if(enable){
                //把所有已经启动过的定时任务启动
                jobManageService.startJob();
            }
        } catch (Exception e) {
            logger.error("启动项目开启定时任务失败!", e);
        }
    }


    /**
     * 定时启动job
     */
    public void startJob(Class job, String cron) throws SchedulerException {
        String jobName = job.getName();
        scheduler = schedulerFactoryBean.getScheduler();
        JobKey jobKey = JobKey.jobKey(jobName + JOB_NAME, jobName + GROUP);
        if (scheduler.getJobDetail(jobKey) != null) {//已经启动过了
            return;
        }
        JobDetail jobDetail = JobBuilder.newJob(job)
                .withIdentity(jobName + JOB_NAME, jobName + GROUP)
                .build();
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(cron);
        CronTrigger cronTrigger = TriggerBuilder.newTrigger()
                .withIdentity(jobName + TRIGGER_NAME, jobName + GROUP)
                .withSchedule(cronScheduleBuilder).build();
        scheduler.scheduleJob(jobDetail, cronTrigger);
    }

    /**
     * 间隔启动job
     */
    public void startJob(Class job, Integer iTimeUnit, Integer interval) throws SchedulerException {
        String jobName = job.getName();
        scheduler = schedulerFactoryBean.getScheduler();
        JobKey jobKey = JobKey.jobKey(jobName + JOB_NAME, jobName + GROUP);
        //已经启动过了
        if (scheduler.getJobDetail(jobKey) != null) {
            return;
        }
        JobDetail jobDetail = JobBuilder.newJob(job).withIdentity(jobName + JOB_NAME, jobName + GROUP).build();
        Date startTime = new Date();
        startTime.setTime(startTime.getTime() + 3000L);//设置三秒后开始执行
        //定义任务调度的时间间隔和次数
        SimpleScheduleBuilder simpleScheduleBuilder = SimpleScheduleBuilder.simpleSchedule();
        //定义时间间隔
        if (iTimeUnit.equals(1)) {//毫秒
            simpleScheduleBuilder = simpleScheduleBuilder.withIntervalInMilliseconds(interval);
        } else if (iTimeUnit.equals(2)) {//秒
            simpleScheduleBuilder = simpleScheduleBuilder.withIntervalInSeconds(interval);
        } else if (iTimeUnit.equals(3)) {//分
            simpleScheduleBuilder = simpleScheduleBuilder.withIntervalInMinutes(interval);
        } else {//小时
            simpleScheduleBuilder = simpleScheduleBuilder.withIntervalInHours(interval);
        }
        //定义重复执行次数是无限次
        simpleScheduleBuilder = simpleScheduleBuilder.withRepeatCount(SimpleTrigger.REPEAT_INDEFINITELY);
        SimpleTrigger trigger = TriggerBuilder.newTrigger()
                .withIdentity(jobName + JOB_NAME, jobName + GROUP)// 定义名字和组
                .startAt(startTime)//定义开始时间
                .withSchedule(simpleScheduleBuilder).build();
        scheduler.scheduleJob(jobDetail, trigger);
    }

    /**
     * description 删除定时任务
     */
    public void deleteJob(Class job) throws SchedulerException {
        String jobName = job.getName();
        JobKey jobKey = JobKey.jobKey(jobName + JOB_NAME, jobName + GROUP);
        if (scheduler.getJobDetail(jobKey) != null) {
            scheduler.deleteJob(jobKey);
        }
    }
}

自定义注解:

package com.rainnie.demo.annotation;

import java.lang.annotation.*;

/**
 * @PackageName: com.rainnie.demo.annotation
 * @ClaseName: CronTask
 * @Description: Custom annotations: add annotation configuration to the timing task implementation class, enable true by default
 * @Author: rainnie
 */
@Target({ ElementType.TYPE })
@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface CronTask {

   /**
    * 排序,默认最大
    * @return
    */
   int index() default 2147483647;

   /**
    * 任务名称
    * @return
    */
   String name() ;

   /**
    * 备注
    * @return
    */
   String remark() default "";

   /**
    * 版本
    * @return
    */
   String version() default "1";

   /**
    * 是否开启 默认开启true
    * @return
    */
   boolean enable() default true;
}

测试类--pojo:

package com.rainnie.demo.pojo;

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

/**
 * @PackageName: com.rainnie.demo.pojo
 * @ClaseName: JobManage
 * @Description: JobManage
 * @Author: zhangyx
 * @Date: 2022/3/26 15:08
 * @params *@params renwu$
 */
public class JobManage implements Serializable {

    private static final long serialVersionUID = 548967589662L;

    private Integer id;
    private Integer iFlag;
    private Long iOrder;
    private String cCreater;
    private Date dCreated;
    private Date dModified;
    private String cEditer;
    private Integer cUserid;
    private String cUsername;
    private String cFromId;

    /**
     * job类名称 C_CLASS_NAME
     */
    private String cClassName;

    /**
     * job业务名称 C_NAME
     */
    private String cName;

    /**
     * job启动类型,1:定时启动,2:间隔启动 I_TYPE
     */
    private Integer iType;

    /**
     * 定时启动时cron表达式 C_CRON
     */
    private String cCron;

    /**
     * 间隔启动时间间隔,单位秒 I_INTERVAL
     */
    private Integer iInterval;

    /**
     * 是否已启动,1:已启动,2:未启动 I_START
     */
    private Integer iStart;

    /**
     * 间隔启动时间单位:1代表毫秒,2代表秒,3代表分,4代表小时
     */
    private Integer iTimeUnit;

    /**
     * 备注 C_MEMO
     */
    private String cMemo;

    public static long getSerialVersionUID() {
        return serialVersionUID;
    }

    public Integer getId() {
        return id;
    }

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

    public Integer getiFlag() {
        return iFlag;
    }

    public void setiFlag(Integer iFlag) {
        this.iFlag = iFlag;
    }

    public Long getiOrder() {
        return iOrder;
    }

    public void setiOrder(Long iOrder) {
        this.iOrder = iOrder;
    }

    public String getcCreater() {
        return cCreater;
    }

    public void setcCreater(String cCreater) {
        this.cCreater = cCreater;
    }

    public Date getdCreated() {
        return dCreated;
    }

    public void setdCreated(Date dCreated) {
        this.dCreated = dCreated;
    }

    public Date getdModified() {
        return dModified;
    }

    public void setdModified(Date dModified) {
        this.dModified = dModified;
    }

    public String getcEditer() {
        return cEditer;
    }

    public void setcEditer(String cEditer) {
        this.cEditer = cEditer;
    }

    public Integer getcUserid() {
        return cUserid;
    }

    public void setcUserid(Integer cUserid) {
        this.cUserid = cUserid;
    }

    public String getcUsername() {
        return cUsername;
    }

    public void setcUsername(String cUsername) {
        this.cUsername = cUsername;
    }

    public String getcFromId() {
        return cFromId;
    }

    public void setcFromId(String cFromId) {
        this.cFromId = cFromId;
    }

    public String getcClassName() {
        return cClassName;
    }

    public void setcClassName(String cClassName) {
        this.cClassName = cClassName;
    }

    public String getcName() {
        return cName;
    }

    public void setcName(String cName) {
        this.cName = cName;
    }

    public Integer getiType() {
        return iType;
    }

    public void setiType(Integer iType) {
        this.iType = iType;
    }

    public String getcCron() {
        return cCron;
    }

    public void setcCron(String cCron) {
        this.cCron = cCron;
    }

    public Integer getiInterval() {
        return iInterval;
    }

    public void setiInterval(Integer iInterval) {
        this.iInterval = iInterval;
    }

    public Integer getiStart() {
        return iStart;
    }

    public void setiStart(Integer iStart) {
        this.iStart = iStart;
    }

    public Integer getiTimeUnit() {
        return iTimeUnit;
    }

    public void setiTimeUnit(Integer iTimeUnit) {
        this.iTimeUnit = iTimeUnit;
    }

    public String getcMemo() {
        return cMemo;
    }

    public void setcMemo(String cMemo) {
        this.cMemo = cMemo;
    }

    @Override
    public String toString() {
        return "JobManage{" +
                "id=" + id +
                ", iFlag=" + iFlag +
                ", iOrder=" + iOrder +
                ", cCreater='" + cCreater + '\'' +
                ", dCreated=" + dCreated +
                ", dModified=" + dModified +
                ", cEditer='" + cEditer + '\'' +
                ", cUserid=" + cUserid +
                ", cUsername='" + cUsername + '\'' +
                ", cFromId='" + cFromId + '\'' +
                ", cClassName='" + cClassName + '\'' +
                ", cName='" + cName + '\'' +
                ", iType=" + iType +
                ", cCron='" + cCron + '\'' +
                ", iInterval=" + iInterval +
                ", iStart=" + iStart +
                ", iTimeUnit=" + iTimeUnit +
                ", cMemo='" + cMemo + '\'' +
                '}';
    }
}

测试类-mapper.java:

package com.rainnie.demo.dao;

import com.rainnie.demo.pojo.JobManage;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;

@Mapper
@Repository
public interface JobManageMapper {
    /**
     *
     * @mbg.generated
     */
    int deleteByPrimaryKey(String id);

    /**
     *
     * @mbg.generated
     */
    int insert(JobManage record);

    /**
     *
     * @mbg.generated
     */
    int insertSelective(JobManage record);

    /**
     *
     * @mbg.generated
     */
    JobManage selectByPrimaryKey(String id);

    /**
     *
     * @mbg.generated
     */
    int updateByPrimaryKeySelective(JobManage record);

    /**
     *
     * @mbg.generated
     */
    int updateByPrimaryKey(JobManage record);

    List<String> selectJobClassName();

    int startOrStopJob(JobManage jobManage);

    int stopJob();

    List<JobManage> selectAll(Map map);
}

测试类-mapper.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.rainnie.demo.dao.JobManageMapper">
  
  <resultMap id="BaseResultMap" type="com.rainnie.demo.pojo.JobManage">
    <id column="ID" jdbcType="VARCHAR" property="id" />
    <result column="C_CLASS_NAME" jdbcType="VARCHAR" property="cClassName" />
    <result column="C_NAME" jdbcType="VARCHAR" property="cName" />
    <result column="I_TYPE" jdbcType="INTEGER" property="iType" />
    <result column="C_CRON" jdbcType="VARCHAR" property="cCron" />
    <result column="I_INTERVAL" jdbcType="INTEGER" property="iInterval" />
    <result column="I_START" jdbcType="INTEGER" property="iStart" />
    <result column="I_TIME_UNIT" jdbcType="INTEGER" property="iTimeUnit" />
    <result column="C_MEMO" jdbcType="VARCHAR" property="cMemo" />
    <result column="I_FLAG" jdbcType="INTEGER" property="iFlag" />
    <result column="I_ORDER" jdbcType="DECIMAL" property="iOrder" />
    <result column="D_CREATED" jdbcType="TIMESTAMP" property="dCreated" />
    <result column="C_CREATER" jdbcType="VARCHAR" property="cCreater" />
    <result column="D_MODIFIED" jdbcType="TIMESTAMP" property="dModified" />
    <result column="C_EDITER" jdbcType="VARCHAR" property="cEditer" />
  </resultMap>
  <sql id="Base_Column_List">
    ID, C_CLASS_NAME, C_NAME, I_TYPE, C_CRON, I_INTERVAL, I_START, I_TIME_UNIT, I_INTERVAL, C_MEMO, I_FLAG, I_ORDER,
    D_CREATED, C_CREATER, D_MODIFIED, C_EDITER
  </sql>
  <select id="selectByPrimaryKey" parameterType="java.lang.String" resultMap="BaseResultMap">
    select 
    <include refid="Base_Column_List" />
    from tbl_job
    where ID = #{id,jdbcType=VARCHAR}
  </select>

  <update id="deleteByPrimaryKey" parameterType="java.lang.String">
    update tbl_job set I_FLAG = 0 where ID = #{id,jdbcType=VARCHAR}
  </update>
  <insert id="insert" parameterType="com.rainnie.demo.pojo.JobManage">
    insert into tbl_job (ID, C_CLASS_NAME, C_NAME, 
      I_TYPE, C_CRON, I_TIME_UNIT, I_INTERVAL,
      C_MEMO, I_ORDER, D_CREATED, C_CREATER)
    values (#{id,jdbcType=VARCHAR}, #{cClassName,jdbcType=VARCHAR}, #{cName,jdbcType=VARCHAR}, 
      #{iType,jdbcType=INTEGER}, #{cCron,jdbcType=VARCHAR}, #{iTimeUnit,jdbcType=INTEGER}, #{iInterval,jdbcType=INTEGER},
      #{cMemo,jdbcType=VARCHAR}, #{iOrder,jdbcType=DECIMAL}, #{dCreated,jdbcType=TIMESTAMP}, #{cCreater,jdbcType=VARCHAR})
  </insert>
  <insert id="insertSelective" parameterType="com.rainnie.demo.pojo.JobManage">
    insert into tbl_job
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="id != null">
        ID,
      </if>
      <if test="cClassName != null">
        C_CLASS_NAME,
      </if>
      <if test="cName != null">
        C_NAME,
      </if>
      <if test="iType != null">
        I_TYPE,
      </if>
      <if test="cCron != null">
        C_CRON,
      </if>
      <if test="iInterval != null">
        I_INTERVAL,
      </if>
      <if test="iStart != null">
        I_START,
      </if>
      <if test="cMemo != null">
        C_MEMO,
      </if>
      <if test="iFlag != null">
        I_FLAG,
      </if>
      <if test="iOrder != null">
        I_ORDER,
      </if>
      <if test="dCreated != null">
        D_CREATED,
      </if>
      <if test="cCreater != null">
        C_CREATER,
      </if>
      <if test="dModified != null">
        D_MODIFIED,
      </if>
      <if test="cEditer != null">
        C_EDITER,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="id != null">
        #{id,jdbcType=VARCHAR},
      </if>
      <if test="cClassName != null">
        #{cClassName,jdbcType=VARCHAR},
      </if>
      <if test="cName != null">
        #{cName,jdbcType=VARCHAR},
      </if>
      <if test="iType != null">
        #{iType,jdbcType=INTEGER},
      </if>
      <if test="cCron != null">
        #{cCron,jdbcType=VARCHAR},
      </if>
      <if test="iInterval != null">
        #{iInterval,jdbcType=INTEGER},
      </if>
      <if test="iStart != null">
        #{iStart,jdbcType=INTEGER},
      </if>
      <if test="cMemo != null">
        #{cMemo,jdbcType=VARCHAR},
      </if>
      <if test="iFlag != null">
        #{iFlag,jdbcType=INTEGER},
      </if>
      <if test="iOrder != null">
        #{iOrder,jdbcType=DECIMAL},
      </if>
      <if test="dCreated != null">
        #{dCreated,jdbcType=TIMESTAMP},
      </if>
      <if test="cCreater != null">
        #{cCreater,jdbcType=VARCHAR},
      </if>
      <if test="dModified != null">
        #{dModified,jdbcType=TIMESTAMP},
      </if>
      <if test="cEditer != null">
        #{cEditer,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.rainnie.demo.pojo.JobManage">
    update tbl_job
    <set>
      <if test="cClassName != null">
        C_CLASS_NAME = #{cClassName,jdbcType=VARCHAR},
      </if>
      <if test="cName != null">
        C_NAME = #{cName,jdbcType=VARCHAR},
      </if>
      <if test="iType != null">
        I_TYPE = #{iType,jdbcType=INTEGER},
      </if>
        C_CRON = #{cCron,jdbcType=VARCHAR},
        I_TIME_UNIT = #{iTimeUnit,jdbcType=INTEGER},
        I_INTERVAL = #{iInterval,jdbcType=INTEGER},
      <if test="iStart != null">
        I_START = #{iStart,jdbcType=INTEGER},
      </if>
      <if test="cMemo != null">
        C_MEMO = #{cMemo,jdbcType=VARCHAR},
      </if>
      <if test="dModified != null">
        D_MODIFIED = #{dModified,jdbcType=TIMESTAMP},
      </if>
      <if test="cEditer != null">
        C_EDITER = #{cEditer,jdbcType=VARCHAR},
      </if>
    </set>
    where ID = #{id,jdbcType=VARCHAR}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.rainnie.demo.pojo.JobManage">
    update tbl_job
    set C_CLASS_NAME = #{cClassName,jdbcType=VARCHAR},
      C_NAME = #{cName,jdbcType=VARCHAR},
      I_TYPE = #{iType,jdbcType=INTEGER},
      C_CRON = #{cCron,jdbcType=VARCHAR},
      I_INTERVAL = #{iInterval,jdbcType=INTEGER},
      I_START = #{iStart,jdbcType=INTEGER},
      C_MEMO = #{cMemo,jdbcType=VARCHAR},
      I_FLAG = #{iFlag,jdbcType=INTEGER},
      I_ORDER = #{iOrder,jdbcType=DECIMAL},
      D_CREATED = #{dCreated,jdbcType=TIMESTAMP},
      C_CREATER = #{cCreater,jdbcType=VARCHAR},
      D_MODIFIED = #{dModified,jdbcType=TIMESTAMP},
      C_EDITER = #{cEditer,jdbcType=VARCHAR}
    where ID = #{id,jdbcType=VARCHAR}
  </update>

    <select id="selectJobClassName" resultType="java.lang.String">
        select C_CLASS_NAME from tbl_job where I_FLAG = -1
    </select>
    <select id="selectAll" parameterType="Integer" resultMap="BaseResultMap">
        select <include refid="Base_Column_List"/> from tbl_job where I_FLAG = -1
        <if test="cKlassName != null">
            and C_CLASS_NAME = #{cKlassName}
        </if>
        <if test="start != null">
            and I_START = #{start}
        </if>
        ORDER BY I_ORDER
    </select>

    <update id="startOrStopJob">
        update tbl_job set
        <choose>
            <when test="iStart == 1">
                I_START = 2
            </when>
            <when test="iStart == 2">
                I_START = 1
            </when>
            <otherwise>
                I_FLAG = -1
            </otherwise>
        </choose>
        where ID = #{id,jdbcType=VARCHAR}
    </update>

    <update id="stopJob">
       update tbl_job set I_START = 2 where I_START = 1
    </update>
</mapper>

测试类-service:

  /**
     * 将已经启动过得任务启动
     */
    void startJob() throws Exception;

测试类-serviceImpl:

package com.rainnie.demo.service.impl;


import com.rainnie.demo.config.SchedulerManager;
import com.rainnie.demo.dao.JobManageMapper;
import com.rainnie.demo.pojo.JobManage;
import com.rainnie.demo.service.JobManageService;
import com.rainnie.demo.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;


@Service
public class JobManageServiceImpl implements JobManageService {

    @Autowired
    private JobManageMapper jobManageMapper;
    @Autowired
    private SchedulerManager schedulerManager;
    
   
    @Override
    public void startJob() throws Exception {
        Map map = new HashMap();
        map.put("start", 1);
        List<JobManage> jobManageList = jobManageMapper.selectAll(map);
        for (JobManage jobManage : jobManageList) {
            String className = jobManage.getcClassName();
            Class<?> jobClass = null;

            if (!StringUtils.isNull(className) && className.indexOf("rainnie") != -1) {
                jobClass = Class.forName(className);
            } else {
                throw new RuntimeException("异常,类不存在请确保classname正确");
            }
            Integer type = jobManage.getiType();
            if (type.equals(1)) {//定时启动
                schedulerManager.startJob(jobClass, jobManage.getcCron());
            } else if (type.equals(2)) {//间隔启动
                schedulerManager.startJob(jobClass, jobManage.getiTimeUnit(), jobManage.getiInterval());
            }
        }
    }


}

最后新建一个任务类:

package com.rainnie.demo.job;


import com.rainnie.demo.annotation.CronTask;
import com.rainnie.demo.dao.ActorMapper;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;


@CronTask(name = "检测任务", enable = true, index = 33)
public class GjCheckExceptionProcessJob implements Job {

    private Logger logger = LoggerFactory.getLogger(GjCheckExceptionProcessJob.class);

    private static boolean flag = true;



    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {

        if(flag) {
            flag = false;
            try {
    
                System.out.println("--------dotosomething:"+new Date());
          
            } catch (Exception e) {
                e.printStackTrace();
                logger.info("定时任务执行检测异常!");
            }
            flag = true;
        }

    }

}

建表语句:

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for tbl_job
-- ----------------------------
DROP TABLE IF EXISTS `tbl_job`;
CREATE TABLE `tbl_job`  (
  `ID` int(11) NOT NULL COMMENT '主键',
  `C_CLASS_NAME` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT 'job类名称',
  `C_NAME` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT 'job业务名称',
  `I_TYPE` int(11) NULL DEFAULT NULL COMMENT 'job启动类型,1:定时启动,2:间隔启动',
  `C_CRON` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '定时启动时cron表达式',
  `I_TIME_UNIT` int(11) NULL DEFAULT NULL COMMENT '间隔启动时间单位:1代表毫秒,2代表秒,3代表分,4代表小时',
  `I_INTERVAL` int(11) NULL DEFAULT NULL COMMENT '间隔启动时间间隔',
  `I_START` int(11) NULL DEFAULT NULL COMMENT '是否已启动,1:已启动,2:未启动',
  `C_MEMO` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '备注',
  `I_FLAG` int(11) NULL DEFAULT NULL COMMENT '数据标识:-1_启用|0_删除|1_禁用',
  `I_ORDER` int(11) NULL DEFAULT NULL,
  `D_CREATED` date NULL DEFAULT NULL COMMENT '创建时间',
  `C_CREATER` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '当前登陆用户id',
  `D_MODIFIED` date NULL DEFAULT NULL COMMENT '修改时间',
  `C_EDITER` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`ID`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;

-- ----------------------------
-- Records of tbl_job
-- ----------------------------
INSERT INTO `tbl_job` VALUES (1, 'com.rainnie.demo.job.GjCheckExceptionProcessJob', 常检测任务', 2, NULL, 2, 20, 1, NULL, -1, 1, '2022-03-29', 'rainnie', '2022-03-29', 'rainnie');

SET FOREIGN_KEY_CHECKS = 1;

启动项目,输入如下:

--------dotosomething:2022-04-11 14:47:21
--------dotosomething:2022-04-11 14:47:41
--------dotosomething:2022-04-11 14:48:01
--------dotosomething:2022-04-11 14:48:21
--------dotosomething:2022-04-11 14:48:41
--------dotosomething:2022-04-11 14:49:01
--------dotosomething:2022-04-11 14:49:21
--------dotosomething:2022-04-11 14:49:41

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值