首先定义一个接口
import org.springframework.scheduling.Trigger;
public interface DynamicCustomTask extends Runnable{
public Trigger getTrigger();
public String getCron();
}
随后进行定义配置类
@Component
@Slf4j
public class DynamicSchedulingConfiguraion implements SchedulingConfigurer{
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
通过容器工具类将该接口的所有实现类找出。
List<DynamicCustomTask> tasks = ApplicationContextUtils.getBeanList(DynamicCustomTask.class);
if(CollectionUtils.isEmpty(tasks)) {
return;
}
tasks.forEach(task -> {
将任务进行注册
taskRegistrar.addTriggerTask(() -> {
try {
task.run();
} catch (Exception e) {
log.error("定时任务%s运行时出现异常,内容为%s", task.getClass().getName(), e.getMessage());
}
}, task.getTrigger());
});
}
}
写个demo
@Component
public class DemoOne implements DynamicCustomTask{
public static volatile String cron = "0/1 * * * * ?";
@Override
public void run() {
System.out.println("任务执行中" + new Date().toString());
}
@Override
public Trigger getTrigger() {
Trigger trigger = new Trigger() {
@Override
public Date nextExecutionTime(TriggerContext triggerContext) {
CronTrigger trigger = new CronTrigger(getCron());
Date nextExec = trigger.nextExecutionTime(triggerContext);
return nextExec;
}
};
return trigger;
}
@Override
public String getCron() {
return cron;
}
}
测试方法
@Test
public void test() throws InterruptedException {
while(true) {
Thread.sleep(1000);
DemoOne.cron = "0/10 * * * * ?";
}
}
运行结果
运行结果
网友评论