首頁  >  文章  >  Java  >  Spring3中使用註解(@Scheduled)建立排程任務的實例詳解

Spring3中使用註解(@Scheduled)建立排程任務的實例詳解

Y2J
Y2J原創
2017-04-27 09:34:291867瀏覽

本篇文章主要介紹了詳解在Spring3中使用註解(@Scheduled)創建計劃任務,具有一定的參考價值,有興趣的小伙伴們可以參考一下。

Spring3中加強了註解的使用,其中計劃任務也得到了增強,現在創建一個計劃任務只需要兩個步驟就完成了:

  1. 創建一個Java類,添加一個無參無返回值的方法,在方法上用@Scheduled註解修飾一下;

  2. 在Spring配置文件中添加三個437d455ddb4c1016e5bcaede7b87630a節點;

最後說明一下,第一步建立的Java類別要成為spring可管理的Bean,可以直接寫在XML裡,也可以@Component一下

範例如下

規劃任務類別:

/** 
 * com.zywang.spring.task.SpringTaskDemo.java 
 * @author ZYWANG 2011-3-9 
 */ 
package com.zywang.spring.task; 

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>

以上是Spring3中使用註解(@Scheduled)建立排程任務的實例詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn