这个问题折腾了一天半,简直太笨了我。网上各种资料都一模一样的不能用。
需求是有一个类随着Tomcat启动而开始执行,之后每隔一段时间循环执行。
方法:
1、制作定时任务Servlet,需要用到java.util.Timer:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.Timer;
public class ServerRun extends HttpServlet{
private Timer timer = null;
public void init(ServletConfig config) throws ServletException{
super.init(config);
timer = new Timer(true);
timer.schedule(new Todo(), 0, 1000*60);
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{}
public void destroy(){}
}
说明:timer.schedul()这个方法可以设定执行的操作,并设定延迟时间和间隔时间。分别对应括号内的三个参数。在Servlet的init方法中用Timer是为了把这个Servlet加入Tomcat启动项之后能执