亚当斯的回答是正确的。如果你真的要自己动手(而不是走石英路),你会想用
ServletContextListener
. 下面是一个使用java.util.timer的示例,它或多或少是scheduledexexutorpool的一个哑版本。
public class TimerTaskServletContextListener implements ServletContextListener
{
private Timer timer;
public void contextDestroyed( ServletContextEvent sce )
{
if (timer != null) {
timer.cancel();
}
}
public void contextInitialized( ServletContextEvent sce )
{
Timer timer = new Timer();
TimerTask myTask = new TimerTask() {
@Override
public void run()
{
System.out.println("I'm doing awesome stuff right now.");
}
};
long delay = 0;
long period = 10 * 1000; // 10 seconds;
timer.schedule( myTask, delay, period );
}
}
然后这会出现在web.xml中
com.TimerTaskServletContextListener
再多点思考的食物!