Spring3.0的task 定时任务

Spring3.0的task,task:annotation-driven/的作用就是开启定时器开关,自动扫描程序中带注解的定时器,不过,要让他起作用还需要以下配置:

① 首先在配置文件头部的必须要有:

xmlns:task="http://www.springframework.org/schema/task"

② 其次xsi:schemaLocation必须为其添加:

xsi:schemaLocation=" http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd"

或者加一个版本号

xsi:schemaLocation=" http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd"

③ 然后spring扫描过程必须涵盖定时任务类所在的目录:

com.task.service属于定时任务类的父级甚至更高级

<context:component-scan base-package="com.task.service" />

④ 然后设置动作启用定时任务:

<task:annotation-driven/>

⑤ 最后一步,设置任务类,添加注解

import org.springframework.scheduling.annotation.Scheduled;

import org.springframework.stereotype.Component;

@Component

public class Test {

@Scheduled(cron = "*/5 * * * * ?")//每隔5秒执行一次

public void test() throws Exception {

System.out.println("sms msg has working!");

}

//@Scheduled(cron = "0 0 1 * * ?")//每天凌晨1点整

//@Scheduled(cron = "0 30 0 * * ?")//每天凌晨0点30分

//@Scheduled(cron = "0 */60 * * * ?")//1小时处理一次

}

⑥ 当定时任务比较多的时候,我们还可以添加以下配置:

<!-- 配置任务线性池 -->

<!-- 任务执行器线程数量 -->

<task:executor id="executor" pool-size="3" />

<!-- 任务调度器线程数量 -->

<task:scheduler id="scheduler" pool-size="3" />

<!-- 启用annotation方式 -->

<task:annotation-driven scheduler="scheduler"

executor="executor" proxy-target-class="true" />

proxy-target-class="true" 与proxy-target-class="false"的区别:

proxy-target-class属性值决定是基于接口的还是基于类的代理被创建。如果proxy-target-class 属性值被设置为true,那么基于类的代理将起作用(这时需要cglib库)。如果proxy-target-class属值被设置为false或者这个属性被省略,那么标准的JDK 基于接口的代理

⑦ 当使用项目集群的时候,注解就要不要用了,改成xml配置方式:

<task:scheduled-tasks scheduler="scheduler">

<!-- xml配置定时器,ref是定时器所在类名,method是定时器方法名 --!>

<task:scheduled ref="reminderProcessor" method="process"

cron="0 0 12 * * ?" />

</task:scheduled-tasks>