在Spring中有两种方式可以实现定时器的功能,分别是Scheduled注释方式和XML配置方式,本博客将介绍如何在Spring中使用采用XML配置的方式实现定时器的功能,代码及相应的解释如下:
代码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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task.xsd">
<bean id="jobDispatcher" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject"><!-- 指定调度对象 -->
<bean class="com.ghj.packageoftimer.SpringTimerTest" />
</property>
<property name="targetMethod" value="test" /><!-- 指定定时器执行调度对象中的那个方法,该方法的访问权限也可以是私有的 -->
<property name="concurrent" value="false" /><!-- 配置job是否可以并行运行 -->
</bean>
<bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
<property name="jobDetail" ref="jobDispatcher" />
<property name="cronExpression" value="0 0/1 * * * ?" /><!-- cronExpression用于指明该方法被调用的时机 -->
</bean>
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list><!-- 通过在list标签中的ref标签可以放置一个或多个触发器 -->
<ref bean="cronTrigger" />
</list>
</property>
</bean>
</beans>
代码2——Spring定时器测试类(SpringTimerTest.java文件):
package com.ghj.packageoftimer;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Spring定时器测试类
*
* @author 高焕杰
*/
public class SpringTimerTest{
/**
* Spring定时器测试方法
*
* @author 高焕杰
*/
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定时器成功启动!!!");
}
}
【0分下载示例资源】