myListener类:
package com.rg.listener;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import com.fastunit.samples.listener.MyTask;
public class myListener implements ServletContextListener {
private Timer timer = null;
public void contextInitialized(ServletContextEvent event) {
timer = new Timer(true);
//启动时间 方法1:
SimpleDateFormat fTime = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
try {
Date d1 = fTime.parse("2011/05/17 14:59:55");
// 设置任务计划,启动和间隔时间 从d1时刻开始,每隔1分钟,执行一次
timer.schedule(new MyTask(), d1, 1*10* 1000);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//启动时间 方法2:
/*
Date d2 = new Date(System.currentTimeMillis() + 1000);
// 设置任务计划,启动和间隔时间
timer.schedule(new MyTask(), d2, 3 * 1000);
*/
}
public void contextDestroyed(ServletContextEvent event) {
timer.cancel();
}
}
myTask类:
package com.rg.listener;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.TimerTask;
import cn.rg.crawlerSpider.getHtml;
public class myTask extends TimerTask {
public void run() {
// System.out.println("call at " + (new Date()));
// TODO 此处添加具体任务代码
System.out.println("begin:");
//---begin--
try {
getHtml.getHtml("http://syc001.iteye.com/admin/blogs/1046615");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//---end--
System.out.println("end:");
}
}
web.xml 配置:
schedule和scheduleAtFixedRate的区别在于,如果指定开始执行的时间在当前系统运行时间之前,scheduleAtFixedRate会把已经过去的时间也作为周期执行,而schedule不会把过去的时间算上。
比如
SimpleDateFormat fTime = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date d1 = fTime.parse("2005/12/30 14:10:00");
t.scheduleAtFixedRate(new TimerTask(){
public void run()
{
System.out.println("this is task you do6");
}
},d1,3*60*1000);
间隔时间是3分钟,指定开始时间是2005/12/30 14:10:00,如果我在14:17:00分执行这个程序,那么会立刻打印3次
this is task you do6 //14:10
this is task you do6 //14:13
this is task you do6 //14:16
并且注意,下一次执行是在14:19 而不是 14:20。就是说是从指定的开始时间开始计时,而不是从执行时间开始计时。
但是上面如果用schedule方法,间隔时间是3分钟,指定开始时间是2005/12/30 14:10:00,那么在14:17:00分执行这个程序,则立即执行程序一次。并且下一次的执行时间是 14:20,而不是从14:10开始算的周期(14:19)。
需要注意的是scheduleAtFixedRate和schedule在参数完全相同的情况下,执行效果是不同的。上面例子中任务只是打印一个字符串,比较简单。但如果任务比较复杂,或者由于任何原因(如垃圾回收或其他后台活动)而延迟了某次执行,则scheduleAtFixedRate方法将快速连续地出现两次或更多的执行,从而使后续执行能够“追赶上来”;而schedule方法的后续执行也将被延迟。所以,在长期运行中,scheduleAtFixedRate执行的频率将正好是指定周期的倒数,schedule 执行的频率一般要稍慢于指定周期的倒数。
scheduleAtFixedRate 效率总体上高于schedule