spring3中使用註解方式實現定時器調度任務

2013-11-05 15:25:42java

1首先在applicationContext.xml中引入spring

1 <!-- 
2 spring3.0註解定時器任務
3 xmlns:task="http://www.springframework.org/schema/task"
4                    
5 http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">
6 -->                    


2打開定時器開關app

不使用註解時,<task:scheduled ref="taskTest" method="hello" cron="10/5 * * * * ?"/>url

<task:scheduled ref = "實體類的beanid" method="方法名" cron="表達式">spa

<!-- 定時器開關 -->
  
  

<task:annotation-driven/>

<!-- cron="10/5 * * * * ?" 每分鐘延遲10秒開始執行,5秒執行一次 <bean id = "taskTest" class="com.test.task.TaskTest"></bean> <task:scheduled-tasks> <task:scheduled ref="taskTest" method="say" cron="10/5 * * * * ?"/> <task:scheduled ref="taskTest" method="hello" cron="10/5 * * * * ?"/> </task:scheduled-tasks> -->

3編寫任務實例
使用註解時在類頭部添加@Component 方法頭部添加@Scheduledcode

package com.test.task;

import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class TaskTest {
    public void say(){
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("時間爲:"+ sdf.format(date));
    }
    
    public void hello(){
        System.out.println("HelloWorld");
    }
    
    @Scheduled(fixedDelay = 5000)  
    void doSomethingWithDelay(){  
        System.out.println("I'm doing with delay now!");  
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("基於註解的定時器啓動,時間爲:"+ sdf.format(date));
    }  
      
    @Scheduled(fixedRate = 5000)  
    void doSomethingWithRate(){  
        System.out.println("I'm doing with rate now!");  
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("基於註解的定時器啓動,時間爲:"+ sdf.format(date));
    }  
      
    @Scheduled(cron = "0/5 * * * * *")  
    void doSomethingWith(){  
        System.out.println("I'm doing with cron now!");  
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("基於註解的定時器啓動,時間爲:"+ sdf.format(date));
    }  

}

經常使用cron 表達式:http://wenku.baidu.com/link?url=mbfyoa3VGn57euEd1jC-VKkrpimxZx7RSLs4VkF_ZCIDna2AnioEIbKnDJDtqfyHtG6X0-LGVcWFmgNQ_slujsISy5iHCRsHEj4UAnHnuXqorm

相關文章
相關標籤/搜索