Spring MVC使用Cron表达式的定时器

来源:互联网 发布:mysql 连接远程数据库 编辑:程序博客网 时间:2024/04/30 01:53

<span style="font-family: tahoma, 宋体; background-color: rgb(250, 250, 252);">Spring MVC的功能非常强大,集成了Quartz定时器的功能,可以通过Cron表达式和简单的注解就实现定时执行任务的功能。</span>

首先在springmvc.xml中添加一下几行:

<span style="white-space:pre"></span>xmlns:task="http://www.springframework.org/schema/task"
<span style="white-space:pre"></span>在xsi:schemaLocation里面添加:
<span style="white-space:pre"></span><pre name="code" class="html"><span style="white-space:pre"></span>http://www.springframework.org/schema/task 
<span style="white-space:pre"></span>http://www.springframework.org/schema/task/spring-task-4.0.xsd"
然后再springmvc.xml里面扫描带注解的文件:

<span style="white-space:pre"><context:component-scan base-package="com.</span>schedule<span style="white-space:pre">"><!-- base-package 如果多个,用“,”分隔 --><span style="white-space:pre"></span><context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/><span style="white-space:pre"></span></context:component-scan></span>
<span style="white-space:pre"></span>
<span style="white-space:pre"></span>定时器配置:
<span style="white-space:pre"></span><!-- 计划任务配置,用 @Service @Lazy(false)标注类,用@Scheduled(cron = "0 0 2 * * ?")标注方法 -->    <span style="white-space:pre"></span><task:executor id="executor" pool-size="10"/> <task:scheduler id="scheduler" pool-size="10"/>   <span style="white-space:pre"></span> <task:annotation-driven scheduler="scheduler" executor="executor" proxy-target-class="true"/>
<span style="white-space:pre"><span style="color: rgb(51, 51, 51); font-family: tahoma, 宋体; font-size: 16px; line-height: 25.600000381469727px; text-align: justify; background-color: rgb(250, 250, 252);">要添加一个aopaliaance.jar,否则会报错:noClassDefoundError:org/aopalliance/aop/Advice</span></span>
到此配置完成。

然后编写代码。

@Component  public class Test{ @Scheduled(cron = "0 0/1 * * * ?") public void run(){  System.out.println(new Date()) ; }}

 
然后每分钟就可以执行一次了。

注意:方法名不能有返回值和参数,不然会有错误。

如果报Only no-arg methods may be annotated with @Scheduled的错误,看看你的方法是不是有参数。

如果报 Only void-returning methods may be annotated with @Scheduled的错误,看看你的方法是不是有返回值。

1 0