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配置实例数据



原文地址:https://www.cnblogs.com/ixixi/p/11655706.html

时间: 2024-08-30 01:21:16

spring boot定时任务的相关文章

Spring Boot定时任务的使用

Spring Boot中配置定时任务极其简单...... import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import java.text.SimpleDateFormat

spring boot.定时任务问题记录(TaskScheduler/ScheduledExecutorService异常)

一.背景 spring boot的定时任务非常简单,只需要在启动类中加上@EnableScheduling注解,然后在对应的方法上配置@Scheduled就可以了,系统会自动处理并按照Scheduled中的配置定时执行方法. 但是在启动项目的时候,发生了很诡异的现象,有两个TaskScheduler/ScheduledExecutorService的异常打印了出来.但是系统并没有受影响,依然正常启动,而且定时任务也是正常执行. 2018-09-29 15:54:05,187 DEBUG main

spring boot 定时任务基于zookeeper的分布式锁实现

基于ZooKeeper分布式锁的流程 在zookeeper指定节点(locks)下创建临时顺序节点node_n 获取locks下所有子节点children 对子节点按节点自增序号从小到大排序 判断本节点是不是第一个子节点,若是,则获取锁:若不是,则监听比该节点小的那个节点的删除事件 若监听事件生效,则回到第二步重新进行判断,直到获取到锁 具体实现 添加Maven依赖: <?xml version="1.0" encoding="UTF-8"?> <

Spring Boot定时任务运行一段时间后自动关闭的解决办法

用Spring Boot默认支持的 Scheduler来运行定时任务,有时在服务器运行一段时间后会自动关闭.原因:Schedule默认是单线程运行定时任务的,即使是多个不同的定时任务,默认也是单线程运行.当线程挂掉时,定时任务也随之终止. 解决方法: 一.改为多线程执行定时任务: 加一个配置类,实现SchedulingConfigurer接口,重写configureTasks方法即可: import org.springframework.context.annotation.Configura

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

Spring Boot 的定时任务: 第一种:把参数配置到.properties文件中: 代码: package com.accord.task; import java.text.SimpleDateFormat; import java.util.Date; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; /** * 从配置

Spring Boot 定时任务 @Scheduled

项目开发中经常需要执行一些定时任务,比如在每天凌晨,需要从 implala 数据库拉取产品功能活跃数据,分析处理后存入到 MySQL 数据库中.类似这样的需求还有许多,那么怎么去实现定时任务呢,有以下几种实现方式. Java 定时任务的几种实现方式 基于 java.util.Timer 定时器,实现类似闹钟的定时任务 使用 Quartz.elastic-job.xxl-job 等开源第三方定时任务框架,适合分布式项目应用 使用 Spring 提供的一个注解: @Schedule,开发简单,使用比

SpringBoot系列:Spring Boot定时任务Spring Schedule

Spring Schedule是Spring提供的定时任务框架,相较于Quartz,Schedule更加简单易用,在中小型应用中,对于大部分需求,Schedule都可以胜任. 一.Spring Schedule使用演示 在 SpringBoot使用Spring Schedule非常简单,因为SpringBoot自身的starter中已经集成了Schedule,而不需要我们做更多的处理. 使用@EnableScheduling注解开启定时功能,该注解可以使用在启动类上,也可以注解于定时任务的类上.

spring boot 定时任务

package com.ict.conf; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; @Configuration @EnableScheduling // 启用定时

spring boot 1.5.4 定时任务和异步调用(十)

上一篇:spring boot1.5.4 统一异常处理(九) 1      Spring Boot定时任务和异步调用 我们在编写Spring Boot应用中经常会遇到这样的场景,比如:我需要定时地发送一些短信.邮件之类的操作,也可能会定时地检查和监控一些标志.参数等. spring boot定时任务spring-boot-jsp项目源码: https://git.oschina.net/wyait/springboot1.5.4.git 1.1  创建定时任务 在Spring Boot中编写定时