Spring3中增強了註解的使用,其中計劃任務也獲得了加強,如今建立一個計劃任務只須要兩步就完成了:java
建立一個Java類,添加一個無參無返回值的方法,在方法上用@Scheduled註解修飾一下;spring
在Spring配置文件中添加三個<task:**** />節點;spa
最後說明一下,第一步建立的Java類要成爲Spring可管理的Bean,能夠直接寫在XML裏,也能夠@Component一下.net
計劃任務類:xml
/**get
* com.zywang.spring.task.SpringTaskDemo.javait
* @author ZYWANG 2011-3-9io
*/class
package com.zywang.spring.task;import
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
/**
* Spring3 @Scheduled 演示
* @author ZYWANG 2011-3-9
*/
@Component
public class SpringTaskDemo {
@Scheduled(fixedDelay = 5000)
void doSomethingWithDelay(){
System.out.println("I'm doing with delay now!");
}
@Scheduled(fixedRate = 5000)
void doSomethingWithRate(){
System.out.println("I'm doing with rate now!");
}
@Scheduled(cron = "0/5 * * * * *")
void doSomethingWith(){
System.out.println("I'm doing with cron now!");
}
}
Spring配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">
<!-- Enables the Spring Task @Scheduled programming model -->
<task:executor id="executor" pool-size="5" />
<task:scheduler id="scheduler" pool-size="10" />
<task:annotation-driven executor="executor" scheduler="scheduler" />
</beans>