接着上一篇<task:annotation-driven>解析,Insight @Scheduled 解析。
1、@Scheduled注解方法的加载
// bean 初始化后触发callback,ScheduledAnnotationBeanPostProcessor完成@Scheduled 的处理
// 参考InitializingBean's afterPropertiesSet
public Object postProcessAfterInitialization(final Object bean, String beanName) {
// ...
ReflectionUtils.doWithMethods(targetClass, new MethodCallback() {
public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
Scheduled scheduled = AnnotationUtils.getAnnotation(method, Scheduled.class);
if (scheduled != null) {
processScheduled(scheduled, method, bean);
annotatedMethods.add(method);
}
}
});
// ...
return bean;
}
根据Scheduled属性构造不同类型的Task(triggerTasks、cronTasks、fixedRateTasks、fixedDelayTasks),然后注册到ScheduledTaskRegistrar,最后由其激活Task。
3、激活Task
registrar.afterPropertiesSet();
public class ScheduledTaskRegistrar implements InitializingBean, DisposableBean {
public void afterPropertiesSet() {
scheduleTasks();
}
/**
* Schedule all registered tasks against the underlying task scheduler.
*/
protected void scheduleTasks() {
long now = System.currentTimeMillis();
if (this.taskScheduler == null) {
// Executors 熟悉吧,JDK自带的并发框架来了。
this.localExecutor = Executors.newSingleThreadScheduledExecutor();
// Executor包装类,实现不同类型task的分发实现,如下述的CronTask
this.taskScheduler = new ConcurrentTaskScheduler(this.localExecutor);
}
// ...
if (this.cronTasks != null) {
// cron 表达式类型的Task处理
for (CronTask task : this.cronTasks) {
// 构造ReschedulingRunnable(task, trigger)真正实现task 调度
this.scheduledFutures.add(this.taskScheduler.schedule(task.getRunnable(), task.getTrigger()));
}
}
// ...
}
}// ReschedulingRunnable见名知义,reuse-schedule
class ReschedulingRunnable extends DelegatingErrorHandlingRunnable implements ScheduledFuture