任务计划
对于任务计划定时执行,JDK提供了java.util.Timer与java.util.TimerTask类。而Timer功能有限,只能指定任务与任务之间的周期,无法指定某个时间点定时执行任务,可以使用Quartz,它提供了更多的任务计划功能。
1:使用TimerTask
A: 定义1个计划任务
package onlyfun.bb.timertask;
import java.util.TimerTask;
/**
* 1:首先定义1个计划任务(Task),继承TimerTask.
* 2:使用ScheduledTimerTask定义任务的执行周期.
* @author Administrator
*
*/
public class DemoTask extends TimerTask {
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("Takk is executed");
}
}
B: 在applicationContext.xml配置如下:
<beans>
<bean id="demoTask" class="onlyfun.bb.timertask.DemoTask"></bean>
<bean id="scheduledTimerTask" class="org.springframework.scheduling.timer.ScheduledTimerTask">
<property name="timerTask" ref="demoTask"></property>
<property name="period" value="1000"></property>
<!--period定义任务执行间隔,单位毫秒-->
<property name="delay" value="1000"></property>
<!--delay定义启动后,在第一次执行任务前要延迟多少毫秒-->
</bean>
<bean id="timerFactoryBean" class="org.springframework.scheduling.timer.TimerFactoryBean">
<property name="scheduledTimerTasks">
<list>
<ref bean="scheduledTimerTask"/>
</list>
</property>
</bean>
注意:
C: 测试
package onlyfun.bb.timertask;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.io.*;
import java.util.Timer;
public class TestDemoTask {
public static void main(String[] args)throws IOException {
// TODO Auto-generated method stub
ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
System.out.println("启动Task:");
System.out.println("请输入 exit 结束Task:");
//A处
BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));
while(true){
if(reader.readLine().equals("exit")) break;
}
//此句可以放在A处
Timer timer=(Timer)context.getBean("timerFactoryBean");
timer.cancel();
} }
2:使用MethodInvokingTimerTaskFactoryBean制订任务
使用Spring,不一定要继承TimerTask来定义1个Task.
Spring也可以使用MethodInvokingTimerTaskFactoryBean类直接指定执行某个对象的方法.
A: 制定任务(普通类,不需要继承TimerTask)
package onlyfun.bb.timertask;
public class DemoTask2 {
public void execute(){
System.out.println("Task is executed without extends TimerTask");
}
}
B: 配置(注意与方法1的比较:粗体部分)
<!-- task: without extends TimerTask -->
<bean id="demoTask2" class="onlyfun.bb.timertask.DemoTask2"></bean>
<bean id="timerTaksBean" class="org.springframework.scheduling.timer.MethodInvokingTimerTaskFactoryBean">
<property name="targetObject" ref="demoTask2"></property>
<property name="targetMethod" value="execute"></property>
</bean>
<bean id="scheduledTimerTask" class="org.springframework.scheduling.timer.ScheduledTimerTask">
<property name="timerTask" ref="timerTaksBean"></property>
<property name="period" value="1000"></property>
<property name="delay" value="1000"></property>
</bean>
<bean id="timerFactoryBean" class="org.springframework.scheduling.timer.TimerFactoryBean">
<property name="scheduledTimerTasks">
<list>
<ref bean="scheduledTimerTask"/>
</list>
</property>
</bean>
C: 测试——与方法1的测试一样。