亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

spring boot task實現動態創建定時任務

標簽:
SpringBoot

在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;/**
 * @author: cent
 * @email: [email protected]
 * @date: 2019/1/16.
 * @description:
 */@Configuration@EnableScheduling@Slf4jpublic class DynamicSchedule implements SchedulingConfigurer {    /**
     * 测试数据,实际可从数据库获取
     */
    private List<Task> 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 {        /**
         * 主键ID
         */
        private int id;        /**
         * 任务名称
         */
        private String name;        /**
         * cron表达式
         */
        private String cron;
    }
}



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


點擊查看更多內容
TA 點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優質文章

正在加載中
軟件工程師
手記
粉絲
47
獲贊與收藏
152

關注作者,訂閱最新文章

閱讀免費教程

  • 推薦
  • 評論
  • 收藏
  • 共同學習,寫下你的評論
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消