• 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


  • 相关阅读:
    Map与对象关系的思考之P1563玩具谜题
    vector性能调优之resize与reserve
    模拟--P1328 生活大爆炸版石头剪刀布 题解
    模拟--P1540 机器翻译
    get、post、put、delete
    Java POI 导出EXCEL经典实现 Java导出Excel弹出下载框(转载)
    Docker(4) 制作镜像
    Git(1) 常用命令
    Linux(1) 常用命令
    Docker(3) 基础知识
  • 原文地址:https://www.cnblogs.com/gavanwanggw/p/6714733.html
Copyright © 2020-2023  润新知