歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Spring MVC使用Cron表達式的定時器

Spring MVC使用Cron表達式的定時器

日期:2017/3/1 9:36:09   编辑:Linux編程

Spring MVC的功能非常強大,集成了Quartz定時器的功能,可以通過Cron表達式和簡單的注解就實現定時執行任務的功能。

網上看到不少例子,但是都不是很全。

閒話少說,首先要在springmvc.xml中添加下面幾行:

xmlns:task="http://www.springframework.org/schema/task"

<!--下面兩行要放在xsi:schemaLocation裡面-->

http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.2.xsd

有了這兩行代碼,就可以在配置文件中添加定時器配置的XML代碼。例子如下:

還是在springmvc.xml裡面,這兩行不用再解釋,讓springmvc知道去哪裡掃描帶注解的文件:

<!-- 注解掃描包 -->
<context:component-scan base-package="com.cmsv2.controller" />

<!-- 第二個注解包,這裡面只有@Scheduled,所以不掃描controller -->
<context:component-scan base-package="com.cmsv2.schedule">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>

<!-- 開啟注解 -->
<mvc:annotation-driven/>

然後在下面加上:

<!-- 定時器配置
task:executor/@pool-size:可以指定執行線程池的初始大小、最大大小
task:executor/@queue-capacity:等待執行的任務隊列的容量
task:executor/@rejection-policy:當等待隊已滿時的策略,分為丟棄、由任務執行器直接運行等方式
-->
<task:scheduler id="scheduler" pool-size="10" />
<task:executor id="executor" keep-alive="3600" pool-size="100-200"
queue-capacity="500" rejection-policy="CALLER_RUNS" />
<task:annotation-driven executor="executor" scheduler="scheduler" />

這幾行從網上copy。

同時還要添加一個aopaliaance.jar,否則會報錯:noClassDefoundError:org/aopalliance/aop/Advice

地址:http://mirrors.ibiblio.org/pub/mirrors/maven2/aopalliance/aopalliance/1.0/

下載後add to buildpath。

至此配置工作完成。

下面開始寫代碼:

import java.util.Date;

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

@Component
public class ScheduledTest2 {

@Scheduled(cron = "0 0/1 * * * ?")
public void runFunction(){
System.out.println(new Date() + " package.controller scheduled test --> mahaha") ;
}

}

然後就OK了!每分鐘執行一次~~~

Spring MVC+Spring3+Hibernate4開發環境搭建 http://www.linuxidc.com/Linux/2013-07/87119.htm

Spring MVC整合Freemarker基於注解方式 http://www.linuxidc.com/Linux/2013-02/79660.htm

基於注解的Spring MVC簡單介紹 http://www.linuxidc.com/Linux/2012-02/54896.htm

Spring MVC 框架搭建及詳解 http://www.linuxidc.com/Linux/2012-01/52740.htm

Copyright © Linux教程網 All Rights Reserved