輕量級Spring定時任務(Spring-task)


Spring3.0以后自主開發的定時任務工具,spring-task,可以將它比作一個輕量級的Quartz,而且使用起來很簡單,除spring相關的包外不需要額外的包,而且支持注解和配置文件兩種形式。

第一種:基於注解
1、spring.xml中對應位置加入
xmlns:task="http://www.springframework.org/schema/task"
 
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.0.xsd
定時任務開關
<task:annotation-driven />
另外,注解掃描是必須的
<context:component-scan base-package="com._21cn.flowgate.*" />
2、任意一個測試類
@Component
public class MyTask {
 
     @Scheduled(cron = "0/3 * * * * ?")
     public void myjob() {
           System. out.println( "task execing ...");
     }


第二種:基於xml配置
 
1、在上面基於注解的配置基礎上加上
(bean路徑指向定時任務執行類)
 <bean id ="taskTest" class= "com._21cn.flowgate.self.web.TaskJob" ></bean >
    <task:scheduled-tasks >   
        <!--這里表示的是每隔5/10秒執行一次   -->    
        <task:scheduled ref ="taskTest" method="show" cron= "*/5 * * * * ?" />   
        <task:scheduled ref ="taskTest" method="print" cron= "*/10 * * * * ?"/>   
    </task:scheduled-tasks >  
2、任意測試類
public class TaskJob {
     void show(){
           System. out.println( "5s 執行一次。。。。" );
     }
     
     void  print(){
           System. out.println( "10s 執行一次。。。。" );
     }
}

【注意】

測試有兩種方式

1、啟動已經配置好的sping項目

2、

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestMain {
    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); 
    }    
}

這種方式,我一直提示類找不到。

可以使用以下方式解決:

1.加上classpath:前綴
ApplicationContext ctx=new  FileSystemXmlApplicationContext("classpath:applicationContext.xml";
2.加上file:把路徑寫全
ApplicationContext ctx=new  ClassPathXmlApplicationContext("ApplicationContext ctx=new  ClassPathXmlApplicationContext("file:F:/workspace/SpringExercis/src/applicationContext.xml");
如果僅僅是測試,最簡單的方法還是把xml放在src下方便

【附】

關於cron表達式,如果不去理解?很容易被用錯

1) 每一位表示的是 [ 秒 分 時 日 月 周 年]

2) The '?' character is allowed for the day-of-month and day-of-week fields. It is used to specify 'no specific value'. This is useful when you need to specify something in one of the two fields, but not the other.

注意着兩個概念 day-of-month /day-of-week

CRON表達式    含義 
"0 0 12 * * ?"    每天中午十二點觸發 
"0 15 10 ? * *"    每天早上10:15觸發 
"0 15 10 * * ?"    每天早上10:15觸發 
"0 15 10 * * ? *"    每天早上10:15觸發 
"0 15 10 * * ? 2005"    2005年的每天早上10:15觸發 
"0 * 14 * * ?"    每天從下午2點開始到2點59分每分鍾一次觸發 
"0 0/5 14 * * ?"    每天從下午2點開始到2:55分結束每5分鍾一次觸發 
"0 0/5 14,18 * * ?"    每天的下午2點至2:55和6點至6點55分兩個時間段內每5分鍾一次觸發 
"0 0-5 14 * * ?"    每天14:00至14:05每分鍾一次觸發 
"0 10,44 14 ? 3 WED"    三月的每周三的14:10和14:44觸發 
"0 15 10 ? * MON-FRI"    每個周一、周二、周三、周四、周五的10:15觸發 

【參考】

http://my.oschina.net/u/559635/blog/389558


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM