标签:
在Spring中有两种方式可以实现定时器的功能,分别是Scheduled注释方式和XML配置方式,本博客将介绍如何在Spring中使用Scheduled注释方式的方式实现定时器的功能,代码及相应的解释如下:
代码1—Spring配置文件(applicationContext.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:task="http://www.springframework.org/schema/task"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.2.xsd">
<!-- 使用annotation 自动注册bean -->
<context:annotation-config />
<!-- 对base-package属性指定的包中的所有类进行扫描,将包中被@Component、@Controller、@Service和@Respositor修饰的类完成bean创建和自动依赖注入。base-package 属性指定了需要扫描的类包,类包及其递归子包中所有的类都会被处理。-->
<context:component-scan base-package="com.ghj"/>
<!-- 设置任务执行者池的大小 -->
<task:executor id="executor" pool-size="5" />
<!-- 设置调度程序池的大小 -->
<task:scheduler id="scheduler" pool-size="10" />
<!-- 采用注解驱动的方式配置Spring定时器 -->
<task:annotation-driven executor="executor" scheduler="scheduler" />
</beans> 注意:请留意上面代码中第05、11、12、21、23和25这6行代码。 代码2——Spring定时器测试类(SpringTimerTest.java文件):
package com.ghj.packageoftimer;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
/**
* Spring定时器测试类
*
* @author 高焕杰
*/
@Component//将本类完成bean创建和自动依赖注入
public class SpringTimerTest{
/**
* Spring定时器测试方法
*
* @author 高焕杰
*/
@Scheduled(cron = "0 0/1 * * * ?")//通过@Scheduled注释将该方法定义为Spring定时调用的方法,其中cron用于指明该方法被调用的时机
public void test(){
System.err.println(new SimpleDateFormat("yyyy 年 MM 月 dd 日 HH 时 mm 分 ss 秒").format(new Date()));
}
}代码3——加载Spring配置文件并启动Spring定时器的类(StartSpringTimer.java文件):
package com.ghj.packageoftest;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* 加载Spring配置文件,启动Spring定时器
*
* @author 高焕杰
*/
public class StartSpringTimer {
public static void main(String[] args){
new ClassPathXmlApplicationContext("conf/spring/applicationContext.xml");
System.out.println("加载Spring配置文件完毕,Spring定时器成功启动!!!");
}
}这种方式实现Spring定时器的优点:
Spring定时器技术终结者——采用Scheduled注释的方式实现Spring定时器
标签:
原文地址:http://blog.csdn.net/gaohuanjie/article/details/43559167