基本概念
任务(job):需要被调度以指定的时间间隔运行的任务单元
触发器(trigger):引发任务运行的条件
调度计划(schedule):一个任务和用来管理这个任务的一组触发器的集合
通常一个任务在他的调度计划中只有一个触发器,所以触发器和调度计划这两个概念通常可以互换。
spring的两种任务调度方法
1.JDK Timer JVM1.3版本后提供的任务调度能力,不需要依赖spring 以外的产品。
优点:被包含在java中,不需要外部依赖库,当受限于程序大小或公司政策时可以使用。
不足:在定义一个调度计划时只能够提供有限的灵活性。
2.Quartz提供很大的灵活性,允许定义类似于真实世界中的触发器。
JDK Timer
1.Timer触发器类型
一次性触发器(one - off)
重复固定延迟触发器(fixed - delay)
重复定时触发器(fixed - rated)
注意:
一次性触发器只能执行一次,执行完成后,不能被再度重新使用;
下面举例说明固定延迟触发器和定时触发器区别:
假设17:00开始执行任务,任务执行时间为30分钟,每小时执行一次,第一次运行将于17:30结束。如果采用固定延迟触发器,第二次运行将在18:30 开始计算方法为前一次结束时间;如果采用定时触发器,第二次运行将在18:00开始,计算方法为前一次开始时间加上间隔时间。
package org.cric.util;
import java.util.TimerTask;
public class HelloTask extends TimerTask {
public void run() {
System.out.println("Hello");
}
}
package org.cric.util;
import java.util.Calendar;
import java.util.Timer;
public class SchedulingTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Timer t = new Timer();
//一次性触发器,1000毫秒开始运行
t.schedule(new HelloTask(), 1000);
//固定时间调用
Calendar calendar = Calendar.getInstance();
calendar.set(2010, Calendar.NOVEMBER, 24, 16, 55, 00);
t.schedule(new HelloTask(), calendar.getTime());
//调用重复任务,固定延迟触发器
t.schedule(new HelloTask(), 1000, 3000);
//定时触发器
t.scheduleAtFixedRate(new HelloTask(), 1000, 1000);
}
}
spring对JDK Timer调度的支持
目的:许多任务需要配置数据,采用spring管理,使得程序易于配置。
触发器信息是编码到程序里的,意味着对任务触发时间的修改都要修改程序并重新编译。
调度新任务或移除任务都需要修改程序代码,这可以通过spring来配置
核心类:
ScheduleTimerTask:扮演着TimerTask的包装器实现,允许你为这个任务定义触发器信息。
TimerFactoryBean:让spring使用配置创建触发器,为一组指定的scheduledTimerTask bean自动创建Timer实例。
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd "> <bean id="helloTask" class="org.cric.util.HelloTask"/> <!-- 包装目标任务--> <bean id="scheduledTask" class="org.springframework.scheduling.timer.ScheduledTimerTask"> <!-- 确定任务调度的延迟时间(毫秒) --> <property name="delay" value="1000"/> <!-- 确定任务调度的间隔时间(毫秒) --> <property name="period" value="2000"/> <!-- 确定任务调度的目标任务 --> <property name="timerTask" ref="helloTask"/> </bean> <!-- 配置启动调度--> <bean id="timerFactory" class="org.springframework.scheduling.timer.TimerFactoryBean"> <!-- 需要启动的任务,该任务已具备调度属性--> <property name="scheduledTimerTasks"> <list> <!-- list列出所有需要调度的任务 --> <ref bean="scheduledTask"/> </list> </property> </bean> </beans>