Spring中的任务调度(一)

在Spring中使用任务调度功能,有二种方式。一种是使用java Timer ,Spring 对该调度API进行了抽象和封装,第二种是使用Quartz框架,Spring也对该框架进了抽象封装。

下面为第一种任务调度方式。

只需自己建二个类即可。

任务类(AddTimerTask.java)

  1. import java.util.TimerTask;
  2. public class AddTimerTask extends TimerTask {//一定行继承TimerTask或其子类 
  3.     private static int result=0;
  4.     @Override
  5.     public void run() {
  6.         System.out.println(result++);
  7.     }
  8. }

主类(SpringTimer.java)

  1. import org.springframework.context.ApplicationContext;
  2. import org.springframework.context.support.ClassPathXmlApplicationContext;
  3. public class SpringTimer {
  4.     /**
  5.      * @param args
  6.      */
  7.     public static void main(String[] args) {
  8.         ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
  9.     
  10.     }
  11. }

配置文件(applicationContext.xml)

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
  3. <beans>
  4.     <bean id="addTimerTask" class="AddTimerTask">       
  5.     </bean> 
  6.     <bean id="scheduledAddTimerTask" class="org.springframework.scheduling.timer.ScheduledTimerTask">
  7.         <property name="timerTask">
  8.             <ref bean="addTimerTask"/>
  9.         </property>
  10.         <property name="delay">
  11.             <value>2000</value>
  12.         </property>
  13.         <property name="period">
  14.             <value>1000</value>
  15.         </property>
  16.     </bean>
  17.     <bean class="org.springframework.scheduling.timer.TimerFactoryBean">
  18.         <property name="scheduledTimerTasks">
  19.             <list>
  20.                 <ref bean="scheduledAddTimerTask"/>
  21.             </list>
  22.         </property>
  23.     </bean>
  24. </beans>

运行结果为:从程序运行后二秒钟开始,每秒钟在控制台打印一个数字,从0开始,不断的加1。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值