zoukankan      html  css  js  c++  java
  • SpringMVC使用Cron表达式的定时器

    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


  • 相关阅读:
    C/C++ 构造函数不能是虚函数
    C/C++ STL迭代器失效
    Linux fork函数
    算法和数据结构 限流算法
    数据库 redis底层实现
    C/C++ 虚析构函数
    万物皆可 Serverless 之使用云函数 SCF 快速部署验证码识别接口
    万物皆可 Serverless 之使用云函数 SCF+COS 免费运营微信公众号
    腾讯云云函数 SCF 日志检索最佳实践
    江娱互动「世界争霸」产品迁移至腾讯云云函数的实践
  • 原文地址:https://www.cnblogs.com/gavanwanggw/p/6714733.html
Copyright © 2011-2022 走看看