今天写了段代码,目的是启动TOMCAT的时候运行一段代码,而且这段代码会每隔一段时间运行一次,但发现有些问题,请各位看看怎么回事?
代码如下:
package com.ee2ee.servlet;
import java.util.TimerTask;
public class TestRun extends TimerTask {
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("the progaram is running");
}
}
package com.ee2ee.servlet;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.Timer;
public class ServletRun extends HttpServlet
{
private HttpServletRequest request;
private PrintWriter out;
//当servlet类被加载时,执行本函数
//在本方法中放置代码即可完成自动加载
public void init(ServletConfig config) throws ServletException
{
//super.init(config);
//此处放置需要自动执行的代码
Timer timer=new Timer();
timer.schedule(new TestRun(), 0, 5000);
System.out.println("*****************I 'm ok now.***************");
}
//Process the HTTP Get request
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
}
//Process the HTTP Post request
//标准的POST方法处理,由http的POST方法触发(调用)
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
}
//Clean up resources
public void destroy()
{
}
}
Tomcat里的web.xml配置如下
ServletRun
com.ee2ee.servlet.ServletRun
1
这段代码运行以后 为什么servlet里的init方法总是运行好几次,并不是一次,这个怎么解决?
运行结果如下:
*****************I 'm ok now.***************
*****************I 'm ok now.***************
*****************I 'm ok now.***************
*****************I 'm ok now.***************
*****************I 'm ok now.***************
*****************I 'm ok now.***************
*****************I 'm ok now.***************
*****************I 'm ok now.***************
the progaram is running
the progaram is running
the progaram is running
the progaram is running
the progaram is running
the progaram is running
the progaram is running
the progaram is running