Spring Task是Spring3.0以后提供的定时任务工具。使用Spring定时任务,除Spring相关的包外不需要添加额外的jar包,支持注解和xml配置两种形式。
准备工作:在Spring配置文件头中添加命名空间xmlns:task及描述。
<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-3.2.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task.xsd">
一.注解形式
1.自动扫描
1.1编写注解的定时任务类
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
/**
* @Auther: DELL-3020
* @Date: 2018/8/22 10:12
* @Description:
*/
@Component
public class TaskDemo {
@Scheduled(fixedRate = 60000)
public void test() throws InterruptedException {
System.out.println("test1:" + Thread.currentThread());
Thread.sleep(100000);
}
@Scheduled(fixedRate = 60000)
public void test2() {
System.out.println("test2:" + Thread.currentThread());
}
}
1.2在spring配置文件中启动注解
<!--自动扫描定时任务类所在的包-->
<context:component-scan base-package="cn.hc.erp.base.timer"/>
<task:annotation-driven/>
<task:annotation-driven/>可以用
<task:scheduler id="myScheduler"/>
<task:annotation-driven scheduler="myScheduler" mode="proxy"/>替代。在<task:scheduler>中可以配置线程池
2.xml配置扫描
2.1编写定时任务类
import org.springframework.scheduling.annotation.Scheduled;
/**
* @Auther: DELL-3020
* @Date: 2018/8/22 11:33
* @Description:
*/
public class TaskDemo2 {
@Scheduled(fixedRate = 60000)
public void test1() {
System.out.println("task1:" + Thread.currentThread());
}
@Scheduled(fixedRate = 60000)
public void test2() {
System.out.println("task2:" + Thread.currentThread());
}
}
2.2在spring配置文件中配置开启定时任务
<bean id="task" class="cn.hc.erp.base.timer.TaskDemo2"/>
<!--<task:annotation-driven/>-->
<task:scheduler id="myScheduler"/>
<task:annotation-driven scheduler="myScheduler" mode="proxy"/>
使用<task:annotation-driven/>可以将后面两行注释掉。
二.xml配置
1.在xml中配置定时任务
1.1编写要启动的定时任务类
public class TaskDemo3 {
public void test1() {
System.out.println("taskDemo1:" + Thread.currentThread());
}
public void test2() {
System.out.println("taskDemo2:" + Thread.currentThread());
}
}
1.2在spring配置文件中配置定时任务
<bean id="taskDemo3" class="cn.hc.erp.base.timer.TaskDemo3"/>
<task:scheduled-tasks>
<task:scheduled ref="taskDemo3" method="test1" fixed-rate="1000"/>
<task:scheduled ref="taskDemo3" method="test2" fixed-rate="1000"/>
</task:scheduled-tasks>
三.其他说明
1.spring定时任务默认是串行的,阻塞式的,默认只开启一个线程。
taskDemo1:Thread[pool-1-thread-1,5,RMI Runtime]
taskDemo2:Thread[pool-1-thread-1,5,RMI Runtime]
taskDemo1:Thread[pool-1-thread-1,5,RMI Runtime]
taskDemo2:Thread[pool-1-thread-1,5,RMI Runtime]
taskDemo1:Thread[pool-1-thread-1,5,RMI Runtime]