框架篇-定时任务(4)-动态定时任务

spring环境下的动态定时任务研究

0.前言

传统spring定时任务采用的是@Sechedu注解去实现,但是该注解只能指定固定的时间任务,例如:配置了2s执行一次,那么永远只能是每两秒执行一次

但是在有些特殊场景下需要一些动态定时任务,例如:最初配置了2s执行一次,在执行任务中,修改配置为5秒执行一次,那么就需要动态的加载配置,使任务动态的变成5s执行一次

1.原理

要想实现动态定时任务,就需要借助SpringSchedulingConfigurer接口,该方式可以实现动态时间,定时任务,具体原理如下图:

image-20210925221827095

时间不一定要存数据库里面,也可以存配置文件或者其他地方,这里数据库只是举了个例子

具体还是要看业务背景,毕竟脱离业务背景单纯搞技术只是纸上谈兵

2.实现

2.0 新建项目

新建一个springboot项目,具体步骤这个不再赘述,其pom.xml内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.2.RELEASE</version>
    </parent>
    <groupId>org.example</groupId>
    <artifactId>task-demo</artifactId>
    <version>1.0-SNAPSHOT</version>


    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

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

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

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.2</version>
        </dependency>
    </dependencies>
</project>

2.1 配置Cron

在数据库中新建表并插入一条数据,如下图所示:

image-20210925222106369

新建pojo和映射接口以及service,如下:

  • pojo

    package com.tomato.bean;
    
    import com.baomidou.mybatisplus.annotation.IdType;
    import com.baomidou.mybatisplus.annotation.TableField;
    import com.baomidou.mybatisplus.annotation.TableId;
    import com.baomidou.mybatisplus.annotation.TableName;
    import lombok.Data;
    
    @Data
    @TableName("cron")
    public class Cron {
        @TableId(type = IdType.AUTO)
        private Integer id;
    
        private String cron;
    }
    
    
  • Mapper

    package com.tomato.mapper;
    
    import com.baomidou.mybatisplus.core.mapper.BaseMapper;
    import com.tomato.bean.Cron;
    
    public interface CronMapper extends BaseMapper<Cron> {
    }
    
    
  • service

    package com.tomato.service;
    
    import com.tomato.bean.Cron;
    import com.tomato.mapper.CronMapper;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import java.util.Optional;
    
    @Service
    @Slf4j
    public class CronService {
        @Autowired
        private CronMapper cronMapper;
    
        public String getCron() {
            // 只是为了测试 固定id
            Cron cron = cronMapper.selectById(1);
            return cron.getCron();
        }
    
    }
    
    
  • application.yml

    image-20210925222430289

2.2 配置解释

2.2.1 SchedulingConfigurer

要想实现定时任务主要是实现SchedulingConfigurer接口,然后重写configureTasks方法。

从源码可知该方法参数为ScheduledTaskRegistrar类型,该参数就是用来注册要执行的定时任务,如下图所示:

image-20210925215957741

2.2.2 ScheduledTaskRegistrar

configureTasks方法中,ScheduledTaskRegistrar通过addTriggerTask来添加触发器任务,从而去执行。

addTriggerTask方法有两个参数,一个是要执行得任务,一个是触发器,如下图:

image-20210925220419604

其实从上图源码中可以知道,调用该方法其本质是构建一个TriggerTask任务,然后添加进去

其中该方法参数如下:

  • task 代表要执行得任务,一个Runable类型

  • trigger 触发器,代表在什么时候触发执行任务,该接口有两个实现类,如下:

    image-20210925220818342

    其中CronTrigger触发器代表cron表达式得触发器,其源码如下:

    image-20210925220923364
    image-20210925221128180

    从源码可知创建该触发器需要传入一个cron表达式

2.3 配置代码

具体配置代码如下:

package com.tomato.config;

import com.tomato.bean.Cron;
import com.tomato.service.CronService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.atomic.AtomicInteger;

@Configuration
@Slf4j
public class SchedulingTaskConfigurer implements SchedulingConfigurer {

    @Autowired
    private CronService cronService;

    private final AtomicInteger number = new AtomicInteger(1);

    /**
     * 该方法就是用来实现定时任务
     * @param taskRegistrar
     */
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.addTriggerTask(() -> {
            log.info("测试任务:{},时间:{}" , number.addAndGet(1), LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        }, triggerContext -> {
            String expression =  cronService.getCron();
            log.info("b:cron:{}", expression);
            // nextExecutionTime 表示下一次任务执行时间
            return new CronTrigger(expression).nextExecutionTime(triggerContext);
        });
    }

}

2.4 启动类代码

在启动类上加上开启定时任务注解@EnableScheduling

package com.tomato;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling
@MapperScan("com.tomato.mapper")
public class TaskApplication {
    public static void main(String[] args) {
        SpringApplication.run(TaskApplication.class, args);

    }
}

3.测试

image.png

这样就完成一个动态定时任务配置

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,088评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,715评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,361评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,099评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 60,987评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,063评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,486评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,175评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,440评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,518评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,305评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,190评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,550评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,880评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,152评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,451评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,637评论 2 335

推荐阅读更多精彩内容