1.servlet 定时器
import java.io.IOException;
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 BlogDailySumServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private Timer timer1 = null;
private BlogDailySumTask task1;
/**
* Constructor of the object.
*/
public BlogDailySumServlet() {
super();
}
/**
* Destruction of the servlet.
*
*/
public void destroy() {
super.destroy();
if (timer1 != null) {
timer1.cancel();
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
// init方法启动定时器
public void init() throws ServletException {
ServletContext context = getServletContext();
// (true为用定时间刷新缓存)
String startTask = getInitParameter("startTask");
// 定时刷新时间(分钟)
Long delay = Long.parseLong(getInitParameter("intervalTime"));
// 启动定时器
if (startTask.equals("true")) {
timer1 = new Timer(true);
task1 = new BlogDailySumTask(context);
timer1.schedule(task1, delay * 60 * 1000, delay * 60 * 1000);
}
}
}
2.业务处理
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.TimerTask;
import javax.servlet.ServletContext;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
public class BlogDailySumTask extends TimerTask {
private ServletContext context;
private Service service;
private static boolean isRunning = true;
public BlogDailySumTask(ServletContext context) {
this.context = context;
}
@Override
public void run() {
if (isRunning) {
ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(context);
service= (Service)ctx.getBean("service");
//business logic
}
}
}
3.web.xml配置
<servlet>
<servlet-name>blogDailySumServlet</servlet-name>
<servlet-class>[package path].BlogDailySumServlet</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>2</load-on-startup>
</servlet>