Spring 任务调度

1. 触发机制
定时任务的触发机制一般可分为两种,分别是按固定周期运行和在指定时间点运行。

2. 依赖 jar 
commons-logging-1.1.1.jar
spring-beans-3.2.3.RELEASE.jar
spring-context-3.2.3.RELEASE.jar
spring-core-3.2.3.RELEASE.jar
spring-expression-3.2.3.RELEASE.jar
# download url
http://www.springsource.org/download/community 
https://dist.apache.org/repos/dist/release/commons/logging/binaries/ 

3. 一个 Java 类

[java]  view plain copy print ?
 
  1. package org.demo.task;  
  2.   
  3. import java.util.Date;  
  4.   
  5. public class HeartBeatTask  
  6. {  
  7.     /** 
  8.      * 检测心跳 
  9.      */  
  10.     public void run()  
  11.     {  
  12.         String time = new Date().toString();  
  13.         System.out.println("[" + time + "] alive.");  
  14.     }  
  15. }  

4. Spring 配置文件 src/spring-tasks.xml

 

[html]  view plain copy print ?
 
  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"   
  4.     xmlns:task="http://www.springframework.org/schema/task"  
  5.     xsi:schemaLocation="  
  6.        http://www.springframework.org/schema/beans  
  7.        http://www.springframework.org/schema/beans/spring-beans.xsd  
  8.        http://www.springframework.org/schema/task  
  9.        http://www.springframework.org/schema/task/spring-task-3.2.xsd" >  
  10.       
  11.     <!-- bean definition -->  
  12.     <bean id="heartBeat" class="org.demo.task.HeartBeatTask" />  
  13.       
  14.     <!-- task definition -->  
  15.     <task:scheduler id="myScheduler" pool-size="10" />  
  16.     <task:scheduled-tasks scheduler="myScheduler">  
  17.         <task:scheduled ref="heartBeat" method="run" initial-delay="10000" fixed-delay="5000" />  
  18.     </task:scheduled-tasks>  
  19.       
  20. </beans>  

# <task:scheduled> 的参数说明如下:
initial-delay :  表示第一次运行前需要延迟的时间,单位是毫秒
fixed-delay   :  表示从上一个任务完成到下一个任务开始的间隔, 单位是毫秒
fixed-rate    :  表示从上一个任务开始到下一个任务开始的间隔, 单位是毫秒
cron          :  cron 表达式,由6个字段组成,依次为 second, minute, hour, day, month, weekday  例如:
                 "0 0 * * * *"                     = the top of every hour of every day.
                 "*/10 * * * * *"                 = every ten seconds.
                 "0 0 8-10 * * *"               = 8, 9 and 10 o'clock of every day.
                 "0 0/30 8-10 * * *"          = 8:00, 8:30, 9:00, 9:30 and 10 o'clock every day.
                 "0 0 9-17 * * MON-FRI" = on the hour nine-to-five weekdays
                 "0 0 0 25 12 ?"              = every Christmas Day at midnight

5. 一个测试类

 

[java]  view plain copy print ?
 
  1. public static void main(String[] args)  
  2. {  
  3.     AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("spring-tasks.xml");  
  4.     System.out.println("context is " + ctx);  
  5. }  

猜你喜欢

转载自1025358610.iteye.com/blog/2066789
今日推荐