码迷,mamicode.com
首页 > 编程语言 > 详细

SpringMVC使用Cron表达式的定时器

时间:2017-04-15 18:28:37      阅读:329      评论:0      收藏:0      [点我收藏+]

标签:sdn   advice   drive   code   报错   mave   caller   task   date   

SpringMVC的功能很强大,集成了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。

至此配置工作完毕。


以下開始写代码:


<span style="font-family: Arial, Helvetica, sans-serif;">import java.util.Date;</span>
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了!每分钟运行一次~~~ 


參考:http://bbs.csdn.net/topics/260068512

http://www.2cto.com/kf/201311/257405.html

http://blog.csdn.net/xiao_wgs69/article/details/11269391


SpringMVC使用Cron表达式的定时器

标签:sdn   advice   drive   code   报错   mave   caller   task   date   

原文地址:http://www.cnblogs.com/gavanwanggw/p/6714733.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!