SpringMvc定时器任务

在最近的工作中,涉及到一个定时任务,由于以前对springMVC使用较少,所以,上网找了一点资料.这个demo感觉挺好,推荐给大家.

使用到的JAR文件:

aopalliance-1.0.jar
commons-logging-1.1.3.jar
spring-aop-3.2.4.RELEASE.jar
spring-beans-3.2.4.RELEASE.jar
spring-context-3.2.4.RELEASE.jar
spring-core-3.2.4.RELEASE.jar
spring-expression-3.2.4.RELEASE.jar
spring-web-3.2.4.RELEASE.jar
spring-webmvc-3.2.4.RELEASE.jar

首先要配置我们的SpringMVC文件

xmlns 加下面的内容、

[xml] 预览复制
 
  1. xmlns:task="http://www.springframework.org/schema/task"  

然后xsi:schemaLocation加下面的内容、

[xml] 预览复制
 
  1. http://www.springframework.org/schema/task  
  2.   
  3. http://www.springframework.org/schema/task/spring-task-3.2.xsd  

最后是我们的task任务扫描注解

[xml] 预览复制
 
  1. <!-- task任务扫描注解 -->  
  2. <task:annotation-driven/>  

我配置的扫描位置是

[xml] 预览复制
 
  1. <context:component-scan base-package="com.wuzhut"></context:component-scan>  

下面写出一个测试类

[java] 预览复制
 
  1. package com.wuzhut.task;  
  2.   
  3. import org.springframework.scheduling.annotation.Scheduled;  
  4. import org.springframework.stereotype.Component;  
  5.   
  6. @Component  
  7. public class MyTask {  
  8.     @Scheduled(cron="0/5 * * * * ? ") //间隔5秒执行  
  9.     public void taskCycle(){  
  10.         System.out.println("无主题(www.wuzhuti.cn) <span style="color: #000000;">专注于前端开发技术和程序开发研究的技术博客</span>");  
  11.     }  
  12. }  

注意

需要注意的几点:

1、spring的@Scheduled注解  需要写在实现上、

2、 定时器的任务方法不能有返回值(如果有返回值,spring初始化的时候会告诉你有个错误、需要设定一个proxytargetclass的某个值为true、具体就去百度google吧)

3、实现类上要有组件的注解@Component

送上demo源码供学习参考:http://pan.baidu.com/s/1mg0yxss

原文地址:https://www.cnblogs.com/skyWings/p/6633014.html