spring配置定时器

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

  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点触发 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值