【README】
本文参考如下文章,使用EnableScheduling注解新增调度任务; (翻译)spring注解接口EnableScheduling说明-CSDN博客文章浏览阅读21次。作为参考,上面例子可以与下面的xml配置做比较。这些示例是等效的,只是在 XML 中使用了固定利率周期而不是自定义触发器实现;这是因为 task: namespace scheduling 无法轻松公开此类支持。这只是一个演示,展示了基于代码的方法如何通过直接访问实际组件来实现最大程度的可配置性。https://blog.csdn.net/PacosonSWJTU/article/details/147029339
【1】调度装配类
/**
* @author Tom
* @version 1.0.0
* @ClassName BusiSchedulerConfig.java
* @Description TODO
* @createTime 2025年04月06日 21:49:00
*/
@Configuration
@EnableScheduling
public class BusiSchedulerConfig implements SchedulingConfigurer {
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.setScheduler(this.taskScheduler());
}
@Bean(name = "taskScheduler", destroyMethod = "shutdown")
public ScheduledThreadPoolExecutor taskScheduler() {
ScheduledThreadPoolExecutor scheduledExecutorService =
new ScheduledThreadPoolExecutor(1, new ThreadPoolExecutor.DiscardPolicy());
return scheduledExecutorService;
}
}
【2】调度任务
@Component
@Slf4j
public class BusiProbeRedisScheduleTask {
@Autowired
@Qualifier("taskScheduler")
private ScheduledThreadPoolExecutor taskScheduler;
@Scheduled(fixedRate = 5000)
public void reportCurTime() {
BlockingQueue<Runnable> queue = taskScheduler.getQueue();
log.info("reportCurTime: curTime = {}, threadName={}, blockQueueSize={}"
, BusiDateTimeUtils.getNowText(), Thread.currentThread().getName(), queue.size());
}
}
【3】运行结果
BusiProbeRedisScheduleTask : reportCurTime: curTime = 2025-04-12 11:52:55, threadName=pool-2-thread-1, blockQueueSize=0
BusiProbeRedisScheduleTask : reportCurTime: curTime = 2025-04-12 11:53:00, threadName=pool-2-thread-1, blockQueueSize=0
BusiProbeRedisScheduleTask : reportCurTime: curTime = 2025-04-12 11:53:05, threadName=pool-2-thread-1, blockQueueSize=0
BusiProbeRedisScheduleTask : reportCurTime: curTime = 2025-04-12 11:53:10, threadName=pool-2-thread-1, blockQueueSize=0
BusiProbeRedisScheduleTask : reportCurTime: curTime = 2025-04-12 11:53:15, threadName=pool-2-thread-1, blockQueueSize=0
BusiProbeRedisScheduleTask : reportCurTime: curTime = 2025-04-12 11:53:20, threadName=pool-2-thread-1, blockQueueSize=0