spring task 基于接口的动态定时任务


 

基于接口(SchedulingConfigurer)

 

@Configuration
@EnableScheduling
public class DynamicScheduleTask implements SchedulingConfigurer {

    /**
     * 动态 执行定时任务.
     */
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {

        List<Map<String, String>> mapList = new ArrayList<>();
        {
            Map<String, String> map = new HashMap<>();
            map.put("id", "1");
            map.put("cron", "0/5 * * * * ?");
            mapList.add(map);
        }
        {
            Map<String, String> map2 = new HashMap<>();
            map2.put("id", "2");
            map2.put("cron", "0/6 * * * * ?");
            mapList.add(map2);
        }
        for (Map<String, String> stringMap : mapList) {
            String id = stringMap.get("id");
            String cron = stringMap.get("cron");

            taskRegistrar.addTriggerTask(
                    //添加任务内容(Runnable)
 () -> System.out.println("执行动态定时任务: " + LocalDateTime.now().toLocalTime()),
            //设置执行周期(Trigger) triggerContext -> { //2.1 从数据库获取执行周期 // TODO //2.2 合法性校验. if (StringUtils.isEmpty(cron)) { // Omitted Code .. } //2.3 返回执行周期(Date) return new CronTrigger(cron).nextExecutionTime(triggerContext); } ); } } }

 

参考文章:https://blog.csdn.net/u013987258/article/details/106671908

源码:https://gitee.com/caoyeoo0/xc-springboot/tree/springTask/

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM