@Configuration
@EnableScheduling
public class CompleteScheduleConfig implements SchedulingConfigurer {
@Mapper
interface CornMapper{
@Select("select cron from cron limit 1")
String getCorn();
}
@Autowired
private CornMapper mapper;
/*public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.addTriggerTask(new Runnable() {
@Override
public void run() {
System.out.println("执行定时任务2: " + LocalDateTime.now().toLocalTime());
}
}, new Trigger() {
@Override
public Date nextExecutionTime(TriggerContext triggerContext) {
String cron = mapper.getCorn();
//2.2 合法性校验.
if (StringUtils.isEmpty(cron)) {
// Omitted Code ..
}
//2.3 返回执行周期(Date)
return new CronTrigger(cron).nextExecutionTime(triggerContext);
}
});
}*/
//lambda方式
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.addTriggerTask(
//1.添加任务内容(Runnable)
() -> System.out.println("执行定时任务2: " + LocalDateTime.now().toLocalTime()),
//2.设置执行周期(Trigger)
triggerContext -> {
//2.1 从数据库获取执行周期
String cron = mapper.getCorn();
//2.2 合法性校验.
if (StringUtils.isEmpty(cron)) {
// Omitted Code ..
}
//2.3 返回执行周期(Date)
return new CronTrigger(cron).nextExecutionTime(triggerContext);
}
);
}
}
SchedulingConfigurer动态定时
最新推荐文章于 2024-07-16 18:15:00 发布