spring3使用task注记及task:annotation-driven解决定时问题

来源:互联网 发布:谷歌读屏软件下载 编辑:程序博客网 时间:2024/06/03 09:15

定义一个定时操作

[java] view plaincopy
  1. package com.jCuckoo.demo;  
  2. import java.text.SimpleDateFormat;  
  3. import java.util.Date;  
  4. import org.springframework.scheduling.annotation.Scheduled;  
  5.   
  6. public class Singer {  
  7.       
  8.       
  9.     //@Scheduled(fixedDelay=1000)  //第一种方式  
  10.     //fixedDelay延时多少毫秒,多少毫秒执行一次  
  11.     @Scheduled(cron="0 * * * * *")     //第二种方式  
  12.   
  13.     /* 
  14.         1 Seconds (0-59) 
  15.         2 Minutes (0-59) 
  16.         3 Hours (0-23) 
  17.         4 Day of month (1-31) 
  18.         5 Month (1-12 or JAN-DEC) 
  19.         6 Day of week (1-7 or SUN-SAT) 
  20.         7 Year (1970-2099) 
  21.         取值:可以是单个值,如6; 
  22.             也可以是个范围,如9-12; 
  23.             也可以是个列表,如9,11,13 
  24.             也可以是任意取值,使用* 
  25.     */  
  26.     //0 * * * * * 代表每分钟执行一次  
  27.     /* 
  28.         2011-09-07 09:23:00 
  29.         2011-09-07 09:24:00 
  30.         2011-09-07 09:25:00 
  31.         2011-09-07 09:26:00 
  32.      */  
  33.     public void singing(){  
  34.         Date date=new Date();  
  35.         SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");  
  36.         System.out.println(sdf.format(date));  
  37.     }  
  38. }  

spring配置文件如下:

[html] view plaincopy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"  
  4.     xmlns:tx="http://www.springframework.org/schema/tx"   
  5.     xmlns:task="http://www.springframework.org/schema/task"  
  6.     xsi:schemaLocation="  
  7. http://www.springframework.org/schema/beans  
  8. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  9. http://www.springframework.org/schema/tx  
  10. http://www.springframework.org/schema/tx/spring-tx-3.0.xsd  
  11. http://www.springframework.org/schema/aop  
  12. http://www.springframework.org/schema/aop/spring-aop-3.0.xsd  
  13. http://www.springframework.org/schema/task  
  14. http://www.springframework.org/schema/task/spring-task-3.0.xsd  
  15. ">  
  16.     <bean id="singer" class="com.jCuckoo.demo.Singer"/>  
  17.     <task:annotation-driven />  
  18. </beans>  

测试类
[java] view plaincopy
  1. package com.jCuckoo.demo;  
  2. import org.springframework.context.ApplicationContext;  
  3. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  4. public class MainTest {  
  5.     public static void main(String[] args) {  
  6.         ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");  
  7.         Singer singer=(Singer) context.getBean("singer");  
  8.     }  
  9. }  

结果:

2011-09-07 09:23:00
2011-09-07 09:24:00
2011-09-07 09:25:00
2011-09-07 09:26:00

0 0
原创粉丝点击