spring boot定时任务

Posted 稚语希听

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring boot定时任务相关的知识,希望对你有一定的参考价值。

1  在启动类上添加:@EnableScheduling // 开启定时任务

2  实现调度器

   

import java.util.Date;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import com.chobits81.cc.component.system.model.GnzlTrigger;
import com.chobits81.cc.component.system.service.DirectDefine;
/**
 * 定时调度器
 * @author Kyoxue
 */
public abstract class GnzlScheduler implements SchedulingConfigurer,DirectDefine{
    private String cron = StringUtils.EMPTY;
    @Override
    public void configureTasks(ScheduledTaskRegistrar arg0) {
        // TODO Auto-generated method stub
        arg0.addTriggerTask(runnable(), shcheduler());
    }
    
    private Runnable runnable() {
        return new Runnable() {
            @Override
            public void run() {
                boolean on = false;
                GnzlTrigger config = setup();
                if (null != config) {
                    //配置修改表达式这里同步更新定时时间
                    cron = StringUtils.trimToEmpty(config.getCron());
                    //任务开关
                    String onoff = config.getOnoff();
                    on = (StringUtils.isNotEmpty(onoff)&&"Y".equalsIgnoreCase(onoff))?true:false;
                }
                if (!on) {
                    LOG.warn("定时开关已关闭!");
                    return;
                }
                task();
            }
        };
    }

    private Trigger shcheduler() {
        return new Trigger() {
            @SuppressWarnings("deprecation")
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext) {
               try {
                   if (!SCHEDULER_SWITCH_ON) {
//                       LOG.warn("定时触发器开关已关闭!");
                       return null;
                   }
                   //第一次springboot启动,初始化触发器,读取配置表达式
                   //初始化表达式如果为空或者格式不准确直接导致任务永久停止
                   //如果配置表没有表达式或错误格式,修改后springboot需要重启,才能启动定时触发器
                   GnzlTrigger config = setup();
                   if (null != config) {
                           cron = StringUtils.trimToEmpty(config.getCron());
                      }
                   CronTrigger trigger = new CronTrigger(cron);
                   return trigger.nextExecutionTime(triggerContext);
                } catch (Exception e) {
                    // TODO: handle exception
                    LOG.error("表达式定义异常!{}",e.getMessage());
                  return null;
                }
                
            }
        };
    }
    /**
     * 读取定时配置
     * @return
     */
    public abstract GnzlTrigger setup();
    /**
     * 覆盖定时内容
     */
    public abstract void task();
}

3 具体任务

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.chobits81.cc.component.system.dao.GnzlTriggerMapper;
import com.chobits81.cc.component.system.model.GnzlLog;
import com.chobits81.cc.component.system.model.GnzlTrigger;
import com.chobits81.cc.component.system.service.impl.DirectLogServiceImpl;
import com.chobits81.cc.component.system.service.impl.DirectMessageQService;
import com.chobits81.cc.component.system.service.impl.DirectMqEnum;
import com.chobits81.cc.component.util.Pagenation;

/**
 * 队列日志入库任务 
 * @author Kyoxue
 * @deprecated
 */
@Service
public class GnzlSchedulerSearchLog2db extends GnzlScheduler{
    
    @Autowired
    private GnzlTriggerMapper gnzlTriggerMapper;
    @Autowired
    private DirectMessageQService directMessageQService;
    @Autowired
    private DirectLogServiceImpl directLogServiceImpl;
    @Override
    public void task() {
        // TODO Auto-generated method stub
        try {
            //task code here...
        } catch (Exception e) {
            // TODO: handle exception
           LOG.error("{}{}异常了!{}",LOG_PREFIX_QNR,LOG_PREFIX_RUN_LOG2DB,e);
        }
    }
    @Override
    public GnzlTrigger setup() {
        // TODO Auto-generated method stub
        try {
            return gnzlTriggerMapper.selectBySName(KEY_GNZL_SEARCH_LOG2DB);
        } catch (Exception e) {
            // TODO: handle exception
            LOG.error("读取配置异常!",e);
        }
        return null;
    }

}

4定时配置表

CREATE TABLE `t_gnzl_trigger` (
  `sname` varchar(20) NOT NULL COMMENT \'定时索引\',
  `cron` varchar(64) NOT NULL COMMENT \'表达式\',
  `switch` char(1) NOT NULL DEFAULT \'N\' COMMENT \'开关 Y|N\',
  `remark` varchar(128) DEFAULT NULL COMMENT \'再次擦除结果 Y:成功 N:失败\',
  `createTime` datetime NOT NULL COMMENT \'录入时间\',
  `creater` varchar(64) NOT NULL DEFAULT \'GNZL\' COMMENT \'录入人\',
  `modifier` varchar(64) DEFAULT NULL,
  `modifyTime` datetime DEFAULT NULL,
  PRIMARY KEY (`sname`),
  UNIQUE KEY `sname` (`sname`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT=\'定时任务表\';

5配置实例数据

 

 



以上是关于spring boot定时任务的主要内容,如果未能解决你的问题,请参考以下文章

Spring Boot 定时+多线程执行

Spring Boot 定时任务单线程和多线程

Spring boot实现定时任务二:使用注解@scheduled和@EnableScheduling

spring boot 整合 quartz 集群环境 实现 动态定时任务配置原

spring-boot实战09:Spring Boot中使用@Scheduled创建定时任务

Spring Boot 中使用 Spring Task 实现定时任务