在Spring中使用JDK定时器实现调度任务

作者:chszs,转载需注明。博客主页: http://blog.csdn.net/chszs

本文探讨Spring如何集成JDK的Timer定时器,实现计划执行任务。

有时候,需要执行一些无用户交互的程序,就像在指定的时间间隔后台运行进程那样。比如,杀毒软件可以每隔2天就在后台运行一次。又比如某些程序每天都要连接一次服务器,查看有没有更新。

本文探讨Spring如何集成JDK的Timer定时器,实现计划执行任务。

一、Spring框架集成JDK的Timer

JDK的Timer任务对象提供了在指定时间执行任何任务的功能。我们来看下面的例子:

假设我们想写一个服务,此服务周期性的检查互联网连接,并用日志记录连接的状态。让我们假定此服务是全天候运行的,且每隔30秒执行一次。

所需要的JAR包如下:

log4j-1.2.13.jar

commons-logging-1.1.1.jar

spring-beans-3.2.4.RELEASE.jar

spring-context-3.2.4.RELEASE.jar

spring-context-support-3.2.4.RELEASE.jar

spring-core-3.2.4.RELEASE.jar

spring-expression-3.2.4.RELEASE.jar

二、写服务类

下面的类实现了互联网连接检查。

Listing 1: CheckInternetConnectionService.java

package com.chszs;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date; public class CheckInternetConnectionService {
public void checkConnection(){
if(doCheck()){
System.out.println(new Date() + "Internet connection available");
}else{
System.out.println(new Date() + "Internet connection not available");
}
} private boolean doCheck(){
URL urlObject = null;
URLConnection urlConnection = null;
try{
urlObject = new URL("http://www.baidu.com");
urlConnection = urlObject.openConnection();
urlConnection.getContent();
return true;
}catch(Exception e){
return false;
}
}
}

上面的代码很简单,doCheck()方法检查互联网连接是否有效。

三、封装定时器任务服务

下面我们写一个服务,实现定时任务。代码如下:

Listing 2: CheckInternetConnectionWithTimerTask

package com.chszs;
import java.util.TimerTask; public class CheckInternetConnectionWithTimerTask extends TimerTask{
private CheckInternetConnectionService service; public CheckInternetConnectionService getService(){
return service;
} public void setService(CheckInternetConnectionService service){
this.service = service;
} @Override
public void run() {
service.checkConnection();
}
}

此类继承了java.util.TimerTask类。

重写了run()方法,可以执行任意操作。这里是调用互联网连接检查。

注意定时器任务依赖于连接服务对象。稍后,我们将看到怎样连线这两个对象。

四、配置

至今,我们还没有指定执行的时间间隔。Spring提供了这样的配置支持。下面我们来看看该如何配置:

Listing 3: timer.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:cache="http://www.springframework.org/schema/cache" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <bean id="connectionCheckService" class="com.chszs.CheckInternetConnectionService">
</bean>
<bean id="connectionCheckTimerTask" class="com.chszs.CheckInternetConnectionWithTimerTask">
<property name="service" ref="connectionCheckService" />
</bean>
<bean id="scheduledConnectionCheckTimerTask" class="org.springframework.scheduling.timer.ScheduledTimerTask">
<property name="delay" value="2000" />
<property name="period" value="30000" />
<property name="timerTask" ref="connectionCheckTimerTask" />
</bean>
<bean class="org.springframework.scheduling.timer.TimerFactoryBean">
<property name="scheduledTimerTasks">
<list>
<ref bean="scheduledConnectionCheckTimerTask" />
</list>
</property>
</bean>
</beans>

以上配置文件的细节:

"connectionCheckService"这个Bean表示互联网连接服务。

"connectionCheckTimerTask"这个Bean定义了定时器任务。由于此定时器任务依赖于"connectionCheckService"这个Bean,故通过配置进行注入。

下面的代码是从Spring框架中声明定时器任务的调度对象:

	<bean id="scheduledConnectionCheckTimerTask" class="org.springframework.scheduling.timer.ScheduledTimerTask">
<property name="delay" value="2000" />
<property name="period" value="30000" />
<property name="timerTask" ref="connectionCheckTimerTask" />
</bean>

org.springframework.scheduling.timer.ScheduledTimerTask这个类提供了对定时任务调度执行的支持。

属性delay的单位是毫秒,它指定任务执行前需要延时多少时间。2000意味着延时2秒开始执行任务。

第二个属性period的单位也是毫秒,它表示任务每隔多少时间就重复执行一次。30000这个值表示每隔30秒执行一次。

最后一个属性是timerTask,它指定实际要执行的任务。

触发调度任务是通过TimerFactoryBean进行的。它可以指定待调度的任务对象列表,尽管这里只有1个待调度的任务对象。

	<bean class="org.springframework.scheduling.timer.TimerFactoryBean">
<property name="scheduledTimerTasks">
<list>
<ref bean="scheduledConnectionCheckTimerTask" />
</list>
</property>
</bean>

五、客户端

客户端程序会载入应用程序的上下文。一旦上下文被载入,服务对象、定时器任务对象、调度的定时器任务对象都会被载入并连线。下面我们继续介绍触发器Bean是如何触发定时器任务的执行,互联网连接在每隔30秒运行一次。

Listing 4: Client.java

package com.chszs;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class Client {
public static void main(String[] args){
ApplicationContext ctx = new ClassPathXmlApplicationContext("timer.xml");
}
}

运行Client.java,可以看到每隔30秒定时器任务就调度执行一次。

执行结果如下:

Sun Aug 11 21:08:26 CST 2013Internet connection available
Sun Aug 11 21:08:56 CST 2013Internet connection available
Sun Aug 11 21:09:26 CST 2013Internet connection available
Sun Aug 11 21:09:56 CST 2013Internet connection available

在Spring中使用JDK定时器实现调度任务的更多相关文章

  1. Spring中的JDK动态代理

    Spring中的JDK动态代理 在JDK1.3以后提供了动态代理的技术,允许开发者在运行期创建接口的代理实例.在Sun刚推出动态代理时,还很难想象它有多大的实际用途,现在动态代理是实现AOP的绝好底层 ...

  2. spring中基于JDK和CGLIB代理在项目的应用

    一.环境与问题 环境 spring boot的版本是1.2.1.RELEASE.JDK版本是1.7 问题 ​ A服务 PeopleService 调用B服务 HelloService ,其中B服务的方 ...

  3. Spring 3 调度器示例 —— JDK 定时器和 Quartz 展示

    Spring框架提供了执行和调度任务的抽象,支持线程池或者在应用服务器环境中代理给CommonJ. Spring也集成了支持使用JDK Timer和Quartz调度库提供的Quartz Schedul ...

  4. Spring中使用Schedule调度

    在spring中两种办法使用调度,以下使用是在spring4.0中. 一.基于application配置文件,配置入下: <bean id="jobDetail" class ...

  5. Spring中Quartz调度器的使用

    一.Quartz的特点 * 按作业类的继承方式来分,主要有以下两种: 1.作业类继承org.springframework.scheduling.quartz.QuartzJobBean类的方式 2. ...

  6. JavaEE开发之Spring中的多线程编程以及任务定时器详解

    上篇博客我们详细的聊了Spring中的事件的发送和监听,也就是常说的广播或者通知一类的东西,详情请移步于<JavaEE开发之Spring中的事件发送与监听以及使用@Profile进行环境切换&g ...

  7. Spring中实现定时调度

    1,   内容简介 所谓的定时调度,是指在无人值守的时候系统可以在某一时刻执行某些特定的功能采用的一种机制,对于传统的开发而言,定时调度的操作分为两种形式: 定时触发:到某一时间点上执行某些处理操作: ...

  8. Spring AOP中的JDK和CGLib动态代理哪个效率更高?

    一.背景 今天有小伙伴面试的时候被问到:Spring AOP中JDK 和 CGLib动态代理哪个效率更高? 二.基本概念 首先,我们知道Spring AOP的底层实现有两种方式:一种是JDK动态代理, ...

  9. Spring中定时器实现

    在Spring 中使用Quartz,本文介绍Spring3.0以后自主开发的定时任务工具,spring task,可以将它比作一个轻量级的Quartz,而且使用起来很简单,除spring相关的包外不需 ...

随机推荐

  1. POJ 2983 Is the Information Reliable?(差分约束系统)

    http://poj.org/problem?id=2983 题意:N 个 defense stations,M条消息,消息有精确和模糊之分,若前边为P.则为精确消息,有两个defense stati ...

  2. POJ 2531 Network Saboteur

    http://poj.org/problem?id=2531 题意 :有N台电脑,每两台电脑之间都有个通信量C[i][j]; 问如何将其分成两个子网,能使得子网之间的通信量最大. 也就是说将所有节点分 ...

  3. MongoDB实战指南(五):MongoDB中的聚集分析

    聚集操作是对数据进行分析的有效手段.MongoDB主要提供了三种对数据进行分析计算的方式:管道模式聚集分析,MapReduce聚集分析,简单函数和命令的聚集分析. 1. 管道模式进行聚集 这里所说的管 ...

  4. Memcached总结二:Memcached环境安装设置以及连接memcache服务器

    1 在Ubuntu上安装Memcached 要在Ubuntu上安装Memcached,打开终端,然后输入以下命令: $sudo apt-get update $sudo apt-get install ...

  5. Android开发规范

    一.Android编码规范 1.java代码中不出现中文,最多注释中可以出现中文 2.局部变量命名.静态成员变量命名 只能包含字母,单词首字母出第一个外,都为大写,其他字母都为小写 3.常量命名 只能 ...

  6. What is martian source / martian packets

    Martian source / Martian packets In Linux, by default, packets are considered individually for routi ...

  7. Oracle 常用符号CHR

    select  chr(92)||chr(102) from dual; \f select  chr(92)||chr(110) from dual; \n select  chr(92)||chr ...

  8. poj2723

    把每对钥匙看做一个变量,那两个钥匙看做他的两个状态 每一个开门的要求就是一个条件(xi or xj) 很显然有了2sat的基本要素 2sat是一个判定性问题,而这题求最多能过几个门: 不难想到二分答案 ...

  9. WordPress OptimizePress插件任意文件上传漏洞

    漏洞版本: WordPress OptimizePress Plugin 1.x 漏洞描述: WordPress是一种使用PHP语言开发的博客平台,用户可以在支持PHP和MySQL数据库的服务器上架设 ...

  10. [NYOJ 15] 括号匹配(二)

    括号匹配(二) 时间限制:1000 ms  |  内存限制:65535 KB 难度:6   描述 给你一个字符串,里面只包含"(",")","[&qu ...