java listener實現定時任務

來源:互聯網
上載者:User

標籤:建立   rate   try   text   job   port   重寫   web.xml   lis   

使用java ServletContextListener 實現各種簡單定時任務。

1. 建立ServletContextListener,在3.0版本的web.xml中不再需要添加listener的聲明。

 1 package com.test.listener; 2  3 import java.text.ParseException; 4 import java.text.SimpleDateFormat; 5 import java.util.Date; 6 import java.util.Timer; 7  8 import javax.servlet.ServletContextEvent; 9 import javax.servlet.ServletContextListener;10 import javax.servlet.annotation.WebListener;11 12 import com.test.job.timerJobTest;13 import com.test.job.timerJobTest2;14 @WebListener("This is my servlet3.0 listener")15 public class MyServletContextListener implements ServletContextListener {16     private Timer timer= null;17     private Timer timer2= null;18     @Override19     public void contextDestroyed(ServletContextEvent arg0) {20         // TODO Auto-generated method stub21         System.out.println("servletContext被銷毀");22     }23 24     @Override25     public void contextInitialized(ServletContextEvent arg0) {26         // TODO Auto-generated method stub27         System.out.println("servletContext 初始化");28         timer= new Timer(true);//建立一個守護線程29         timer2= new Timer(true);30         timerJobTest tjb = new timerJobTest(); //建立要隨容器啟動的定時任務131         timerJobTest2 tjb2= new timerJobTest2();//建立要隨容器啟動的定時任務232         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");33         Date d1=null;34         try {35             d1 = sdf.parse("2016-08-01 21:28:10");36         } catch (ParseException e) {37             // TODO Auto-generated catch block38             e.printStackTrace();39         }40         timer.schedule(tjb, d1);//任務1是指定時間執行41         timer2.schedule(tjb2, 10*1000, 20*1000);//任務2是容器啟動10秒以後,每20秒執行一次42     }43 }

2.建立任務類,任務類是繼承了TimerTask 類,並重寫了run方法,run方法中就是需要執行的程式碼片段,也可以直接調用其他類

 1 package com.test.job; 2  3 import java.util.TimerTask; 4  5 public class timerJobTest extends TimerTask { 6  7     @Override 8     public void run() { 9         // TODO Auto-generated method stub10         System.out.println("定時任務1任務被執行");11         12     }13 14 }
 1 package com.test.job; 2  3 import java.util.TimerTask; 4  5 public class timerJobTest2 extends TimerTask { 6  7     @Override 8     public void run() { 9         // TODO Auto-generated method stub10         System.out.println("定時任務2任務被執行");11         12     }13 14 }

 

java listener實現定時任務

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.