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/

原文地址:https://www.cnblogs.com/ooo0/p/14029750.html