栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java > SpringBoot

spring boot task实现动态创建定时任务

SpringBoot 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

spring boot task实现动态创建定时任务

在Spring Boot项目中,通过@EnableScheduling可启用Spring自带的定时任务支持,在通过@Scheduled注解定义定时任务,但是通过注解只能编写固定时间的定时任务,无法动态调整定时间隔,可通过实现SchedulingConfigurer接口实现动态定时任务注册。

参考代码:

package org.cent.demo.scanner.schedule;import lombok.AllArgsConstructor;import lombok.Data;import lombok.extern.slf4j.Slf4j;import org.springframework.context.annotation.Configuration;import org.springframework.scheduling.Trigger;import org.springframework.scheduling.annotation.EnableScheduling;import org.springframework.scheduling.annotation.SchedulingConfigurer;import org.springframework.scheduling.config.ScheduledTaskRegistrar;import org.springframework.scheduling.support.CronTrigger;import java.util.Arrays;import java.util.List;@Configuration@EnableScheduling@Slf4jpublic class DynamicSchedule implements SchedulingConfigurer {    
    private List tasks = Arrays.asList(            new Task(1, "任务1", "*/30 * * * * *"),            new Task(2, "任务2", "*/30 * * * * *"),            new Task(3, "任务3", "*/30 * * * * *"),            new Task(4, "任务4", "*/30 * * * * *"),            new Task(5, "任务5", "*/30 * * * * *"),            new Task(6, "任务6", "*/30 * * * * *"),            new Task(7, "任务7", "*/30 * * * * *"),            new Task(8, "任务8", "*/30 * * * * *"),            new Task(9, "任务9", "*/30 * * * * *"),            new Task(10, "任务10", "*/30 * * * * *")
    );    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        tasks.forEach(task -> {            //任务执行线程
            Runnable runnable = () -> log.info("execute task {}", task.getId());            //任务触发器
            Trigger trigger = triggerContext -> {                //获取定时触发器,这里可以每次从数据库获取最新记录,更新触发器,实现定时间隔的动态调整
                CronTrigger cronTrigger = new CronTrigger(task.getCron());                return cronTrigger.nextExecutionTime(triggerContext);
            };            //注册任务
            scheduledTaskRegistrar.addTriggerTask(runnable, trigger);
        });

    }    @Data
    @AllArgsConstructor
    static class Task {        
        private int id;        
        private String name;        
        private String cron;
    }
}



作者:centychen
链接:https://www.jianshu.com/p/546631cc2b8f


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/234873.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号