其他分享
首页 > 其他分享> > 定时任务不在硬编码,动态定时刷起来

定时任务不在硬编码,动态定时刷起来

作者:互联网

前言

问题描述

简介

传统定时器

@Component
public class SimpleSchedule {

    @Autowired
    TestMapper testMapper;

    @Scheduled(cron = "*/6 * * * * ?")
    private void process() {
        List<Test> tests = testMapper.getTests();
        System.out.println(tests);
    }
}


@SpringBootApplication
public class CrontabApplication {
    public static void main(String[] args) {
        SpringApplication.run(CrontabApplication.class, args);
    }
}

#动态定时器

V1.0


@Configuration
public class ScheduleConfigV1 implements SchedulingConfigurer {

    @Autowired
    CronMapper cronMapper;
    @Autowired
    TestMapper testMapper;
    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        scheduledTaskRegistrar.addTriggerTask(()-> {
                    System.out.println("执行定时器任务:" + LocalDateTime.now().toLocalTime());
                    List<Test> tests = testMapper.getTests();
                    System.out.println(tests);
                },
                triggerContext -> {
                    List<Cron> crons = cronMapper.getCron();
                    Cron cron = crons.get(0);
                    return new CronTrigger(cron.getCron()).nextExecutionTime(triggerContext);
                });
    }
}


V2.0

Registar


public void addCronTask(Runnable task, String cron) {
    addCronTask(new CronTask(task,cron));
}


public ScheduledTask scheduleCronTask(CronTask cronTask) {
    ScheduledTask scheduledTask;
    scheduledTask = new ScheduledTask();
    scheduledTask.future = this.taskScheduler.schedule(cronTask.getRunnable(), cronTask.getTrigger());
    return scheduledTask;
  }


public final class ScheduledTask {

    public volatile ScheduledFuture<?> future;
    /**
     * 取消定时任务
     */
    public void cancel() {
        ScheduledFuture<?> future = this.future;
        if (future != null) {
            future.cancel(true);
        }
    }
}


SchedulingRunnable task = new SchedulingRunnable(TestMapper.class, "getTests", null);
cronTaskRegistrar.addCronTask(task, "0/10 * * * * ?");

#总结

-上面的代码已经上传值gitee
点我传送
https://gitee.com/zxhTom/crontab.git

标签:编码,定时器,cron,刷起来,任务,定时,执行,public
来源: https://blog.csdn.net/u013132051/article/details/117410345