web.xml的配置
<servlet>
<description>定时发信</description>
<display-name>定时发信</display-name>
<servlet-name>TaskMail</servlet-name>
<servlet-class>com.servlet.web.task.TaskMail</servlet-class>
<init-param>
<param-name>startTask</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>intervalTime</param-name>
<param-value>1</param-value>
</init-param>
<load-on-startup>300</load-on-startup>
</servlet>
Servlet
package com.servlet.web.task;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Timer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class TaskMail extends HttpServlet {
private Timer timer1 = null;
private Task task1;
/**
* Constructor of the object.
*/
public TaskMail() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy();
if(timer1!=null){
timer1.cancel();
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost...
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the POST method");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
System.out.println("定时发信启动");
ServletContext context = getServletContext();
// (true为用定时间刷新缓存)
String startTask = getInitParameter("startTask");
// 定时刷新时间(分钟)
Long delay = Long.parseLong(getInitParameter("intervalTime"));
// 启动定时器
if(startTask.equals("true")){
timer1 = new Timer(true);
task1 = new Task(context);
timer1.schedule(task1, delay * 60 * 1000, delay * 60 * 1000);
}
}
}
要执行的任务
package com.servlet.web.task;
import java.util.TimerTask;
import javax.servlet.ServletContext;
public class Task extends TimerTask{
private ServletContext context;
private static boolean isRunning = true;
public Task(ServletContext context){
this.context = context;
}
@Override
public void run() {
if(isRunning){
//context.getContextPath();
System.out.println("定时发信执行");
}
}
}