springboot动态定时任务


spring boot通过注解@EnableScheduling@Scheduled实现的是静态定时任务,不能动态添加、停止、修改等.
本文通过ThreadPoolTaskScheduler实现定时任务动态增删改.

  1. 创建ThreadPoolTaskScheduler

    @Bean
    public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
     ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
     threadPoolTaskScheduler.setPoolSize(10);
     threadPoolTaskScheduler.setRemoveOnCancelPolicy(true);
     return threadPoolTaskScheduler;
    }
  2. 创建一个全局任务记录表

    @Data
    public class Tasks {
     public static Map<String, ScheduledFuture<?>> tasks = new ConcurrentHashMap<>();
    }
  3. 创建一个任务类

    public class MyRunnable implements Runnable {
     private String id;
    
     public MyRunnable(String id) {
         this.id = id;
     }
    
     @Override
     public void run() {
         System.out.println("id: " + this.id + " - " + new Date());
     }
    }
  4. 通过接口启动/删除/修改定时任务

    任务的元数据信息可以保存在数据库中.

    @RestController
    public class DynamicTask {
     @Autowired
     private ThreadPoolTaskScheduler threadPoolTaskScheduler;
    
     // 增加一个带id的定时任务
     @RequestMapping("/start")
     public String startCron(@RequestParam("id") String id) {
         if (Tasks.tasks.containsKey(id)) {
             return "exist";
         }
         ScheduledFuture<?> future = threadPoolTaskScheduler.schedule(new MyRunnable(id), new CronTrigger("0/5 * * * * *"));
         Tasks.tasks.put(id, future);
         return "start";
     }
    
     //根据id删除一个定时任务
     @RequestMapping("/stop")
     public String stopCron(@RequestParam("id") String id) {
         if (!Tasks.tasks.containsKey(id)) {
             return "not exist";
         }
         Tasks.tasks.get(id).cancel(true);
         Tasks.tasks.remove(id);
         return "stop";
     }
    
     //根据id修改定时任务
     @RequestMapping("/changeCron10")
     public String startCron10(@RequestParam("id") String id) {
         stopCron(id);// 先停止,在开启.
         ScheduledFuture<?> future = threadPoolTaskScheduler.schedule(new MyRunnable(id), new CronTrigger("*/10 * * * * *"));
         Tasks.tasks.put(id, future);
         return "change";
     }
    }

文章作者: wuzhiyong
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 wuzhiyong !
评论
  目录