蝈蝈大王

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

spring定时器写在web工程中

配置文件的名字如上

配置文件的内容下面:

<?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.xsd
    http://www.springframework.org/schema/task  
    http://www.springframework.org/schema/task/spring-task-3.1.xsd">

    <task:annotation-driven/> 
     <!-- 此处对于定时时间的配置会被注解中的时间配置覆盖,因此,以注解配置为准 -->  
    <task:scheduled-tasks scheduler="myScheduler">  
        <!-- 规定运行时间 -->
        <task:scheduled ref="TestJob" method="execute" cron="1/5 * * * * *"/>
        <!-- 按间隔时间 -->
        <task:scheduled ref="TestJob" method="execute" fixed-rate="50000" fixed-delay="300"/>
    </task:scheduled-tasks>  
    
    <task:scheduler id="myScheduler" pool-size="10"/>  
</beans>

配置文件说明:

ref是工作类

method是工作类中要执行的方法

initial-delay是任务第一次被调用前的延时,单位毫秒

fixed-delay是上一个调用完成后再次调用的延时

fixed-rate是上一个调用开始后再次调用的延时(不用等待上一次调用完成)

cron是表达式,表示在什么时候进行任务调度。

 

测试类:

package com.um.job;
import org.springframework.stereotype.Component;
//指定定时器名称
@Component("TestJob")  
public class TestJob {
    private static int counter = 0;
    public void execute() {
        System.out.println("定时器开始执行");
    }
}

 将Job.xml引入spring配置文件

<!-- 模块化处理spring定时任务 -->
<import resource="classpath:config/spring-context-job.xml"></import>

posted on 2016-08-31 18:41  蝈蝈大王  阅读(218)  评论(0编辑  收藏  举报