使用spring自带的轻量级调度系统进行任务调度和终止
1.TimedTask 任务调度
代码如下:
@Component
public class TimedTask {
//得到Bean的后置处理器ScheduledAnnotationBeanPostProcessor,用于终止定时任务
@Autowired
private ScheduledAnnotationBeanPostProcessor postProcessor;
private Integer y = 5;
// cron生成器在线生成网址: https://cron.qqe2.com/
@Scheduled(cron = "0/5 * * * * ? ")
public void printTask(){
y--;
System.out.println(y);
if(y == 0){
System.out.println("结束此次定时任务");
cancelScheduledTasks();
}
}
/**
* 通过 ScheduledAnnotationBeanPostProcessor 终止所有定时任务
* 非常暴力,不推荐使用
*/
public void cancelScheduledTasks() {
// 拿到所有的task(带包装)
Set<ScheduledTask> tasks = postProcessor.getScheduledTasks();
if(null != tasks && tasks.size() > 0){
tasks.stream().forEach(task -> {
Task t = task.getTask();
ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) t.getRunnable();
//task所关联的对象,就是带@Scheduled方法的类
Object taskObject = runnable.getTarget();
// 调用postProcessBeforeDestruction()方法,将task移除并cancel
postProcessor.postProcessBeforeDestruction(taskObject, "scheduledTasks");
});
}
}
}
2.主启动类开启@EnableScheduling
代码如下:
@EnableScheduling
@SpringBootApplication
public class AppTest {
public static void main(String[] args) {
SpringApplication.run(AppTest.class, args);
}
}
3.执行结果
4
3
2
1
0
结束此次定时任务