TestContextServletListener
package com.yyy.listener;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Timer;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import com.yyy.schedule.MyTimeTask;
/**
* Application Lifecycle Listener implementation class TestContextServletListener
*
*/
@WebListener
public class TestContextServletListener implements ServletContextListener {
/**
* Default constructor.
*/
public TestContextServletListener() {
// TODO Auto-generated constructor stub
}
/**
* @see ServletContextListener#contextDestroyed(ServletContextEvent)
*/
public void contextDestroyed(ServletContextEvent arg0) {
// TODO Auto-generated method stub
}
/**
* @see ServletContextListener#contextInitialized(ServletContextEvent)
*/
public void contextInitialized(ServletContextEvent arg0) {
// TODO Auto-generated method stub
//创建一个定时器对象
Timer timer=new Timer();
//从当前时间开始 每隔1秒钟调用一次任务,每次执行时间为上一次任务开始起向后推一个period间隔
//timer.scheduleAtFixedRate(new MyTimeTask(), new Date(), 1000);
//timer.schedule(new MyTimeTask(), new Date(), 1000);
//延时指定的时间 执行任务
//timer.schedule(new MyTimeTask(), 60*1000);
//在指定的时间执行某个任务
try {
timer.schedule(new MyTimeTask(), new SimpleDateFormat("HH:mm:ss").parse("20:00:00"),24*3600*1000);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
MyTimeTask
package com.yyy.schedule;
import java.text.SimpleDateFormat;
import java.util.TimerTask;
public class MyTimeTask extends TimerTask {
//重写run方法
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("当前任务的执行时间为:"+new SimpleDateFormat("HH:mm:ss").format(this.scheduledExecutionTime()));
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}