@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);
}
}
@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);
});
}
}
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
原文链接:
https://www.cnblogs.com/zhangxinhua/p/14830103.html
如果觉得本文对你有帮助,可以转发关注支持一下