spring配置定时器

来源:互联网 发布:sqlserver删除表数据 编辑:程序博客网 时间:2024/06/16 03:20

今天配置定时器,看了网上的教程,没有一个成功的,最后还是看了同事的才好的,就写下记录下。

  1. 在web.xml里面,把定时器的配置文件添加进扫描列表。

    <context-param><param-name>contextConfigLocation</param-name><param-value>    classpath:/applicationContext.xml</param-value>


    如果你配置了contextConfigLocation,则会报错,这个时候,吧配置文件添加到上个配置文件后面就好了。

    <context-param><param-name>contextConfigLocation</param-name><param-value>      classpath:/applicationContext.xml,classpath:/spring-context-task.xml</param-value>

  2. 配置文件 spring-context-task.xml 内容

    <?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation="        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd        http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd"   default-lazy-init="true"><description>Spring task</description><!-- 计划任务配置,用 @Service @Lazy(false)标注类,用@Scheduled(cron = "0 0 2 * * ?")标注方法 --><task:executor id="executor" pool-size="10"/><task:scheduler id="scheduler" pool-size="10"/><task:annotation-driven scheduler="scheduler" executor="executor" proxy-target-class="true"/>    <!--id后面是用定时启动的类名 class 后面是要定时启动的类的命令空间加上类名-->    <bean id="getWeightInfo" class="com.inter3i.demo.preopendata.calculate.job.getWeightInfo"></bean>   <task:scheduled-tasks>    <!--这里表示每分钟执行一次-->    <!-- ref后面是要定时启动的类名,和上面的id后面的一样,method后面是类下面要定时启动的方法   -->    <task:scheduled ref="getWeightInfo" method="testGetWeightInfo" cron="0 */1 * * * ?" /></task:scheduled-tasks>

3.getWeightInfo类

package com.inter3i.demo.preopendata.calculate.job;/** * Created by koreyoshi on 2017/5/19. */public class getWeightInfo {    public  void  testGetWeightInfo(){        System.out.println("呵呵哒~~");        //要定时处理的逻辑    }}

4.crond参数

一个cron表达式有至少6个(也可能7个)有空格分隔的时间元素。
按顺序依次为
秒(0~59)
分钟(0~59)
小时(0~23)
天(月)(0~31,但是你需要考虑你月的天数)
月(0~11)
天(星期)(1~7 1=SUN 或 SUN,MON,TUE,WED,THU,FRI,SAT)
年份(1970-2099)

由于”月份中的日期”和”星期中的日期”这两个元素互斥的,必须要对其中一个设置?.

*/1 *  *  *  * ?                 每秒执行一次*  */1 *  *  * ?                 每分钟执行一次0  0   10  *  * ?                 每天上午10点执行一次0  */5 14,18 * * ?           每天下午2点到2:55期间和下午6点到6:55期间的每5分钟触发 "0  0  10  ?  *  MON" 每星期一的上午10点触发