http://wangguorui89.javaeye.com/blog/428345
關鍵字: java, 定時器, timertask
在web中,定時器的啟動一般隨web server的啟動而啟動,一般有兩種方法.
方法一:在web.xml里配置一個Servlet,并設置其隨web server的啟動而啟動。然后在該Servlet的init()方法里啟動定時器,在destory()方法里銷毀定時器。
方法二:在web.xml里配置一個Listener,然后在該Listener的初始化方法里啟動定時器,在其銷毀的方法朝左銷毀定時器。
在servlet中啟動定時器
java 代碼
- import java.io.IOException;
- import java.util.Timer;
- import javax.servlet.RequestDispatcher;
- import javax.servlet.ServletContext;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
-
- import org.apache.commons.lang.StringUtils;
-
- public class ConvergeDataServlet extends HttpServlet {
-
- private static final long serialVersionUID = 1L;
-
- private Timer timer1 = null;
-
- private Task task1;
-
- /**
- * Constructor of the object.
- */
- public ConvergeDataServlet() {
- 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("delay"));
-
- // 啟動定時器
- if(startTask.equals("true")){
- timer1 = new Timer(true);
- task1 = new Task(context);
- timer1.schedule(task1, delay * 60 * 1000, delay * 60 * 1000);
- }
- }
- }
定時執行操作
java 代碼
-
- /**
- *
- * @author callan
- */
- 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){
-
- }
- }
-
- }
在web.xml配置這個servlet為服務啟動時就調用servlet
<servlet></servlet>
< servlet >
< servlet-name >taskservlet< / servlet-name >
< servlet-class >com.task< /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></servlet>