《pro Spring》学习笔记之使用JDK Timer调度任意任务

Spring对Timer的支持核心是由ScheduledTimerTask和TimerFactoryBean类组成,前者扮演后者一个wrapper的角色,通过 TimerFactoryBean,你能够让Spring使用配置创建触发器,为一指定的ScheduledTimerTask bean自动创建Timer实例

我们一般可以编写TimerTask的类,或者ScheduledTimerTas类的子类,实现其run或者getDelay方法来完成具体的定时任务,但是,基于POJ的设计原则,我们希望对一个普通的java中的方法,进行调度,该如何处理呢,请看以下代码

 

POJO:

 

package  ch14.AnyTimerTask;

import  java.util.TimerTask;


import  java.util.TimerTask;

    
public   class  HelloWorldTask  {
        
public void someJob(String message) {
            System.out.println(message);

        }


    }



 

配置文件

核心是MethodInvokingTimerTaskFactoryBean

 

<? xml version="1.0" encoding="UTF-8" ?>
< beans
    
xmlns ="http://www.springframework.org/schema/beans"
    xmlns:xsi
="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation
="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd" >

< bean  id ="target"  class ="ch14.AnyTimerTask.HelloWorldTask" >
</ bean >

< bean  id ="task"  class ="org.springframework.scheduling.timer.MethodInvokingTimerTaskFactoryBean" >
   
< property  name ="targetObject" >
     
< ref  bean ="target" />
   
</ property >
   
< property  name ="targetMethod" >
     
< value > someJob </ value >
   
</ property >
   
< property  name ="arguments" >
     
< value > hello world 3q! </ value >
   
</ property >
</ bean >

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

< bean  id ="timerFactory"  class ="org.springframework.scheduling.timer.TimerFactoryBean" >
  
< property  name ="scheduledTimerTasks" >
    
< ref  bean ="timerTask" />
  
</ property >
</ bean >
</ beans >

 

测试代码:

 

package  ch14.AnyTimerTask;

import  org.springframework.context.ApplicationContext;
import  org.springframework.context.support.ClassPathXmlApplicationContext;

public   class  Test  {

    
/**
     * 
@param args
     
*/

    
public static void main(String[] args) throws Exception{
        ApplicationContext context
=new ClassPathXmlApplicationContext("ch14/AnyTimerTask/applicationContext.xml");
        System.in.read();
        

    }


}

 

运后可以看到,延迟1000毫秒后,每个2000毫秒便运行一次somJob方法,其中我们用arguments参数定义了方法的参数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值