定时器操作

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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值