loushang 2016(基於spring3.2)的定時任務配置---spring task

一直對定時任務充滿好奇,但一直沒有對其進行深入研究,趁項目空暇時間稍微研究下定時任務的使用,因項目基於spring3.2完全支持spring task定時任務,爲方便起見,就是用spring task來進行定時任務設置,目前有兩種實現方法,一種是通過註解(@Scheduled)實現,另一種是直接在xml文件裏配置但無論哪一種方式都得在掃描的xml配置。

首先看下路徑:
早配置掃描時進行配置定時任務,如下:


springtask.xml的配置如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.1.xsd
">
<!-- 註解的開關 -->
<context:annotation-config />
<!-- 註釋資源掃描包路徑 -->
<context:component-scan base-package="dsrw.test" />
<!-- xml配置類的定時執行 -->
<task:annotation-driven />
<!-- 此處的id也可以使用在class裏面使用@Component("myTaskXml")實現-->
<bean id="myTaskXml" class="dsrw.test.taskxml"></bean>

<--通過配置xml實現定時執行, 這裏表示的是每隔五秒執行一次 -->
<!-- 
<task:scheduled-tasks> 
<task:scheduled ref="myTaskXml" method="方法名" cron="*/5 * * * * ?" />
<task:scheduled ref="myTaskXml" method="job3" cron="*/10 * * * * ?"/>
</task:scheduled-tasks>
--> 
</beans> 



附dsrwtestimp.java的代碼---《註解方式》
package dsrw.test;

import java.text.SimpleDateFormat;
import java.util.Locale;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

@Service
public class dsrwtestimp implements Idsrwtest {
@Scheduled(cron="0/5 * * * * ? ")
public void job1() {
String time = new SimpleDateFormat("MMM d,yyyy KK:mm:ss a",Locale.ENGLISH).format(System.currentTimeMillis());
System.out.println("任務進行1:"+time);
}
}


myTaskXml.java的代碼如下----《xml裏面配置方法》
package dsrw.test;
import java.text.SimpleDateFormat;
import java.util.Locale;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component("myTaskXml")
public class taskxml {
public void job2() {
System.out.println("任務進行2中。。。");
}
@Scheduled(cron="0/5 * * * * ? ")
public void job3() {
String time = new SimpleDateFormat("MMM d,yyyy KK:mm:ss a",Locale.ENGLISH).format(System.currentTimeMillis());
System.out.println("任務進行3:"+time);
}
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章