承接前文Spring源码情操陶冶#task:executor解析器,在前文基础上解析我们常用的spring中的定时任务的节点配置。备注:此文建立在spring的4.2.3.RELEASE版本

附例

Spring中的定时任务基本配置样例如下

<!--create schedule thread pool-->
<task:scheduler id="baseScheduler" pool-size="5"></task:scheduler> <!--define bean for schedule task-->
<bean id="taskBean" class="com.jing.test.spring.task.TaskBean"></bean> <!--apply schedule action to above taskBean-->
<task:scheduled-tasks scheduler="baseScheduler">
<task:scheduled ref="taskBean" method="doInit" cron="0 0 0 ? * *"></task:scheduled> <task:scheduled ref="taskBean" method="doClear" cron="0 0 23 ? * *"></task:scheduled>
</task:scheduled-tasks>

其中task:scheduler的配置是不必须的,并且由上述配置可知Spring配置的定时任务可细化到具体的类方法,有更好的扩展性

task:scheduler节点配置的作用

task:scheduler的节点配置与前文所提及的task:executor节点类似,均是创建线程池,那么有什么不同呢,我们可以稍微简单的看下其解析类org.springframework.scheduling.config.SchedulerBeanDefinitionParser的两个方法

	@Override
protected String getBeanClassName(Element element) {
return "org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler";
} @Override
protected void doParse(Element element, BeanDefinitionBuilder builder) {
String poolSize = element.getAttribute("pool-size");
if (StringUtils.hasText(poolSize)) {
builder.addPropertyValue("poolSize", poolSize);
}
}

恩,也就是我们直接关注ThreadPoolTaskScheduler这个类即可。看下其是如何创建线程池的

	/**
* Create a new {@link ScheduledExecutorService} instance.
* <p>The default implementation creates a {@link ScheduledThreadPoolExecutor}.
* Can be overridden in subclasses to provide custom {@link ScheduledExecutorService} instances.
* @param poolSize the specified pool size
* @param threadFactory the ThreadFactory to use
* @param rejectedExecutionHandler the RejectedExecutionHandler to use
* @return a new ScheduledExecutorService instance
* @see #afterPropertiesSet()
* @see java.util.concurrent.ScheduledThreadPoolExecutor
*/
protected ScheduledExecutorService createExecutor(
int poolSize, ThreadFactory threadFactory, RejectedExecutionHandler rejectedExecutionHandler) { return new ScheduledThreadPoolExecutor(poolSize, threadFactory, rejectedExecutionHandler);
}

即默认创建的是ScheduledThreadPoolExecutor线程池,创建核心线程个数为pool-size指定的大小(默认为1),最大线程为Integer.MAX_VALUE,队列为DelayQueue,拒绝策略为AbortPolicy。详情读者可自行阅读

task:sheduled-tasks解析器

配置相应的定时任务,细化到任何bean的方法可直接关联定时器。我们同样观察其主要的两个方法getBeanClassName()doParse()方法

	@Override
protected String getBeanClassName(Element element) {
return "org.springframework.scheduling.config.ContextLifecycleScheduledTaskRegistrar";
}

即实例化并启动定时任务由ContextLifecycleScheduledTaskRegistrar类来执行,我们稍后再谈

	@Override
protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
builder.setLazyInit(false); // lazy scheduled tasks are a contradiction in terms -> force to false
// 存放不同类型定时任务集合
ManagedList<RuntimeBeanReference> cronTaskList = new ManagedList<RuntimeBeanReference>();
ManagedList<RuntimeBeanReference> fixedDelayTaskList = new ManagedList<RuntimeBeanReference>();
ManagedList<RuntimeBeanReference> fixedRateTaskList = new ManagedList<RuntimeBeanReference>();
ManagedList<RuntimeBeanReference> triggerTaskList = new ManagedList<RuntimeBeanReference>();
// 解析子节点task:scheduled
NodeList childNodes = element.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
Node child = childNodes.item(i);
if (!isScheduledElement(child, parserContext)) {
continue;
}
Element taskElement = (Element) child;
String ref = taskElement.getAttribute("ref");
String method = taskElement.getAttribute("method"); // ref 和 method属性必须同时指定,表示对哪个方法关联定时器
if (!StringUtils.hasText(ref) || !StringUtils.hasText(method)) {
parserContext.getReaderContext().error("Both 'ref' and 'method' are required", taskElement);
// Continue with the possible next task element
continue;
} String cronAttribute = taskElement.getAttribute("cron");
String fixedDelayAttribute = taskElement.getAttribute("fixed-delay");
String fixedRateAttribute = taskElement.getAttribute("fixed-rate");
String triggerAttribute = taskElement.getAttribute("trigger");
String initialDelayAttribute = taskElement.getAttribute("initial-delay"); boolean hasCronAttribute = StringUtils.hasText(cronAttribute);
boolean hasFixedDelayAttribute = StringUtils.hasText(fixedDelayAttribute);
boolean hasFixedRateAttribute = StringUtils.hasText(fixedRateAttribute);
boolean hasTriggerAttribute = StringUtils.hasText(triggerAttribute);
boolean hasInitialDelayAttribute = StringUtils.hasText(initialDelayAttribute); // 必须指定cron/fixed-delay/fixed-rate/trigger属性
if (!(hasCronAttribute || hasFixedDelayAttribute || hasFixedRateAttribute || hasTriggerAttribute)) {
parserContext.getReaderContext().error(
"one of the 'cron', 'fixed-delay', 'fixed-rate', or 'trigger' attributes is required", taskElement);
continue; // with the possible next task element
} //initial-delay属性不与cron/trigger属性搭配
if (hasInitialDelayAttribute && (hasCronAttribute || hasTriggerAttribute)) {
parserContext.getReaderContext().error(
"the 'initial-delay' attribute may not be used with cron and trigger tasks", taskElement);
continue; // with the possible next task element
} // 将bean类下的method方法包装成ScheduledMethodRunnable.class实体类
String runnableName =
runnableReference(ref, method, taskElement, parserContext).getBeanName(); if (hasFixedDelayAttribute) {
// 包装成IntervalTask类
fixedDelayTaskList.add(intervalTaskReference(runnableName,
initialDelayAttribute, fixedDelayAttribute, taskElement, parserContext));
}
if (hasFixedRateAttribute) {
// 包装成IntervalTask类
fixedRateTaskList.add(intervalTaskReference(runnableName,
initialDelayAttribute, fixedRateAttribute, taskElement, parserContext));
}
if (hasCronAttribute) {
// 包装成CronTask类
cronTaskList.add(cronTaskReference(runnableName, cronAttribute,
taskElement, parserContext));
}
if (hasTriggerAttribute) {
// 包装成TriggerTask类
String triggerName = new RuntimeBeanReference(triggerAttribute).getBeanName();
triggerTaskList.add(triggerTaskReference(runnableName, triggerName,
taskElement, parserContext));
}
}
// scheduler属性
String schedulerRef = element.getAttribute("scheduler");
if (StringUtils.hasText(schedulerRef)) {
builder.addPropertyReference("taskScheduler", schedulerRef);
}
builder.addPropertyValue("cronTasksList", cronTaskList);
builder.addPropertyValue("fixedDelayTasksList", fixedDelayTaskList);
builder.addPropertyValue("fixedRateTasksList", fixedRateTaskList);
builder.addPropertyValue("triggerTasksList", triggerTaskList);
}

代码过长,此处作下小总结

  1. 定时任务的初始化与实例是由org.springframework.scheduling.config.ContextLifecycleScheduledTaskRegistrar类来加载执行

  2. task:scheduled-tasks的子节点名为task:scheduled

  3. task:scheduled中的refmethod属性是必填项,其会包装成ScheduledMethodRunnable对象;必须指定cron/fixed-delay/fixed-rate/trigger其中之一属性

  4. task-scheduledinitial-delay属性不必填,但其不和cron/trigger属性搭配使用

  5. task:scheduled中的cron代表cron表达式,为字符串形式;fixed-delayfixed-rate可与initial-delay搭配使用,一般选择其中一种即可,为数字形式;trigger代表的是触发器,其关联bean,字符串形式

  6. 根据第五点,具体的任务包装类分别为CronTaskIntervalTaskTriggerTask

ContextLifecycleScheduledTaskRegistrar-定时任务初始化

其默认实现了SmartInitializingSingletonafterSingletonsInstantiated()方法

	@Override
public void afterSingletonsInstantiated() {
scheduleTasks();
}

直接查看父类的schduleTasks()方法

	protected void scheduleTasks() {
long now = System.currentTimeMillis();
// 如果不指定scheduler属性,则默认使用单线程池模型
if (this.taskScheduler == null) {
this.localExecutor = Executors.newSingleThreadScheduledExecutor();
this.taskScheduler = new ConcurrentTaskScheduler(this.localExecutor);
}
// trigger集合和cron集合统一调用任务定时器的schedule()方法
if (this.triggerTasks != null) {
for (TriggerTask task : this.triggerTasks) {
this.scheduledFutures.add(this.taskScheduler.schedule(
task.getRunnable(), task.getTrigger()));
}
}
if (this.cronTasks != null) {
for (CronTask task : this.cronTasks) {
this.scheduledFutures.add(this.taskScheduler.schedule(
task.getRunnable(), task.getTrigger()));
}
}
// fixedRate集合和fixedDelayTasks集合则分别调用任务定时器的scheduleAtFixedRate()和scheduleAtFixedDelay()方法
if (this.fixedRateTasks != null) {
for (IntervalTask task : this.fixedRateTasks) {
if (task.getInitialDelay() > 0) {
Date startTime = new Date(now + task.getInitialDelay());
this.scheduledFutures.add(this.taskScheduler.scheduleAtFixedRate(
task.getRunnable(), startTime, task.getInterval()));
}
else {
this.scheduledFutures.add(this.taskScheduler.scheduleAtFixedRate(
task.getRunnable(), task.getInterval()));
}
}
}
if (this.fixedDelayTasks != null) {
for (IntervalTask task : this.fixedDelayTasks) {
if (task.getInitialDelay() > 0) {
Date startTime = new Date(now + task.getInitialDelay());
this.scheduledFutures.add(this.taskScheduler.scheduleWithFixedDelay(
task.getRunnable(), startTime, task.getInterval()));
}
else {
this.scheduledFutures.add(this.taskScheduler.scheduleWithFixedDelay(
task.getRunnable(), task.getInterval()));
}
}
}
}

由上述代码可以得出,如果task:scheduled-tasks不指定scheduler属性,则默认会采用org.springframework.scheduling.concurrent.ConcurrentTaskScheduler任务定时器来管理任务集合,反之一般则是由org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler任务定时器来管理任务集合

小结

本文则是解析了task:scheduled-tasktask:scheduler节点的配置,具体的任务是如何被执行的,怎么控制定时任务,请见下文针对org.springframework.scheduling.concurrent.ConcurrentTaskScheduler的解读。

Spring源码情操陶冶#task:scheduled-tasks解析器的更多相关文章

  1. Spring源码情操陶冶-AnnotationConfigBeanDefinitionParser注解配置解析器

    本文承接前文Spring源码情操陶冶-自定义节点的解析,分析spring中的context:annotation-config节点如何被解析 源码概览 对BeanDefinitionParser接口的 ...

  2. Spring源码情操陶冶-ComponentScanBeanDefinitionParser文件扫描解析器

    承接前文Spring源码情操陶冶-自定义节点的解析,本文讲述spring通过context:component-scan节点干了什么事 ComponentScanBeanDefinitionParse ...

  3. Spring源码情操陶冶-PropertyPlaceholderBeanDefinitionParser注解配置解析器

    本文针对spring配置的context:property-placeholder作下简单的分析,承接前文Spring源码情操陶冶-自定义节点的解析 spring配置文件应用 <context: ...

  4. Spring源码情操陶冶-AOP之ConfigBeanDefinitionParser解析器

    aop-Aspect Oriented Programming,面向切面编程.根据百度百科的解释,其通过预编译方式和运行期动态代理实现程序功能的一种技术.主要目的是为了程序间的解耦,常用于日志记录.事 ...

  5. Spring源码情操陶冶-自定义节点的解析

    本文承接前文Spring源码情操陶冶-DefaultBeanDefinitionDocumentReader#parseBeanDefinitions,特开辟出一块新地来啃啃这块有意思的骨头 自定义节 ...

  6. Spring源码情操陶冶#task:executor解析器

    承接Spring源码情操陶冶-自定义节点的解析.线程池是jdk的一个很重要的概念,在很多的场景都会应用到,多用于处理多任务的并发处理,此处借由spring整合jdk的cocurrent包的方式来进行深 ...

  7. SpringMVC源码情操陶冶-ResourcesBeanDefinitionParser静态资源解析器

    解析mvc:resources节点,控制对静态资源的映射访问 查看官方注释 /** * {@link org.springframework.beans.factory.xml.BeanDefinit ...

  8. Spring源码情操陶冶-AOP之Advice通知类解析与使用

    阅读本文请先稍微浏览下上篇文章Spring源码情操陶冶-AOP之ConfigBeanDefinitionParser解析器,本文则对aop模式的通知类作简单的分析 入口 根据前文讲解,我们知道通知类的 ...

  9. Spring源码情操陶冶-任务定时器ConcurrentTaskScheduler

    承接前文Spring源码情操陶冶#task:scheduled-tasks解析器,本文在前文的基础上讲解单核心线程线程池的工作原理 应用附例 承接前文的例子,如下 <!--define bean ...

随机推荐

  1. 【Spring源码分析】.properties文件读取及占位符${...}替换源码解析

    前言 我们在开发中常遇到一种场景,Bean里面有一些参数是比较固定的,这种时候通常会采用配置的方式,将这些参数配置在.properties文件中,然后在Bean实例化的时候通过Spring将这些.pr ...

  2. ES6学习总结一(变量;箭头函数;解构赋值)

    一.变量 var  1 可以重复声明(var a=1;var a=7;)(一开始用着会觉得限制很少,但是在大型项目会麻烦,人多嘴杂的时候定义重复了就容易出问题还不好找) 2 无法限制修改 3 没有块级 ...

  3. jquery pjax 用法总结

    以前我们点击a链接的时候总是会刷新整个页面并跳转到新页面,中间可以很明显的看到短暂的白屏.pjax就很好的解决了这问题. pjax的原理很简单,就是发送一个ajax请求,获取html代码,再把相关代码 ...

  4. windows下 python3.5+tensorflow 安装

    个人随笔,备忘参考 首先最近的tensorflow 对python3.5.x友好,我先装了Python3.6,查其他的一些博客说出现问题,后来重装3.5.0.下载用迅雷,超快. 安装比较简单,官网下载 ...

  5. 自创最精简的python装饰器

    个人心血原创,欢迎转载,请注明作者和出处.否则依法追究法律责任!!!! author:headsen  chen date:2018-03-21  10:37:52 代码: 代码解析过程:1,def ...

  6. Python 基础语法复习

    由于选修了<人工智能模式识别>的课程,要求用phthon来实现算法,乘着周三晚上没课,就来回顾一下python的主要语法. 环境:   Anaconda    Python3.6 1.变量 ...

  7. HashMap源码解析(JDK1.8)

    package java.util; import sun.misc.SharedSecrets; import java.io.IOException; import java.io.Invalid ...

  8. angularJS前台传list数组,后台springMVC接收数组

    有时候需要在前台自定义对象,然后把对象封装在list中,在传送到后台,这样的思想也比较合理 1. 前台代码 $scope.saveScore = function () { $scope.userSc ...

  9. npm scripts 使用指南

    转载自:http://www.ruanyifeng.com/blog/2016/10/npm_scripts.html Node 开发离不开 npm,而脚本功能是 npm 最强大.最常用的功能之一. ...

  10. Java中的懒汉式单例与饿汉式单例实例详解

    懒汉式单例:线程非安全,当被调用的时候才创建实例,效率较高 public class LazySingleton { private static LazySingleton lazySingleto ...