3. spring版 timer HelloWorld

本文介绍如何使用Spring框架实现定时任务,包括配置Spring依赖、创建定时任务类、编写Spring配置文件及测试代码等步骤。
1. 由于这回需要使用Spring的jar包,所以需要修改pom文件,添加如下依赖:

<!-- Spring framework -->

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring</artifactId>

<version>2.5.6</version>

</dependency>


注:如果使用3.0版本就不是只改个版本号的问题了,因为spring3.0已经分包了。

2. 编写Timer类代码:

package com.helloworld.common;


public class SayHelloTask{


public void sayHello() {

System.out.println("HelloWorld");

}


}


注意:此domain类完全没有依赖任何接口!!!
3. 编写spring配置文件:这个代码比较多就不全贴上去了
<bean id="sayHelloTask" class="com.helloworld.common.SayHelloTask" />

首先是上面那个bean的声明。
<bean id="schedulerTask" class="org.springframework.scheduling.timer.MethodInvokingTimerTaskFactoryBean">
<property name="targetObject" ref="sayHelloTask" />
<property name="targetMethod" value="sayHello" />
</bean>
MethodInvokingTimerTaskFactoryBean 取代了JDK中的TimerTask

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

这个取代了JDK中的Timer
<bean class="org.springframework.scheduling.timer.TimerFactoryBean">
<property name="scheduledTimerTasks">
<list>
<ref local="timerTask" />
</list>
</property>
</bean>

定义一个TimerFactoryBean来启动Task。
4. 编写测试代码:
public class Test {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("Spring-Scheduler.xml");

}
}

OK 一切运行成功。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值