去哪網實習總結:開發定時任務(JavaWeb)

來源:互聯網
上載者:User

標籤:java   java web   定時任務   定時發送郵件   

本來是以做資料採礦的目的進去哪網的,結構卻成了系統開發。。。

不過還是比較認真的做了三個月,老師很認同我的工作態度和成果。。。

實習馬上就要結束了,總結一下幾點之前沒有注意過的變成習慣和問題,分享給大家。


同時打個廣告:去哪網內審部招JavaWeb開發實習生,時間非常自由,每周一天、周六周日甚至都可以,時間充裕的小夥伴給我留言啊,掙個零花錢,還能長點經驗。。。。(保研的、想工作的大四狗最合適不過了。。。)




其實定時任務很簡單,js其實也做過,就是Timer類的 Timer.schedule(TimerTask task, Date time, long period)方法而已,三個參數分別是:任務、延遲、間隔。

給個完整的代碼:

首先是BugXmlTimer類:

public class BugXmlTimer  {public Timer timer;public void timerStart(){timer = new Timer();Date datetime=new Date();Date midnightDate=new Date();SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");    try {    midnightDate = sdf2.parse(sdf1.format(datetime)+" 10:06:00");    } catch (ParseException e) {        // TODO Auto-generated catch block        e.printStackTrace();    }    System.out.println("before task");    long time = midnightDate.getTime()-datetime.getTime();    //立刻執行,然後每隔10s執行一次    timer.schedule(new BugXmlTimerTask(), 0, 10000);//time}   public void timerStop(){if(timer!=null) timer.cancel();}   public static void main(String[] args){BugXmlTimer myTimer=new BugXmlTimer();        // TODO Auto-generated method stub        myTimer.timerStart();   }}


其次是TimerTask類:
<pre name="code" class="java">public class BugXmlTimerTask extends TimerTask {    @Override    public void run() {    System.out.print("run task");    try {<strong>sendMail();//下一篇部落格教你發送郵件</strong>} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}}

最後添加Listener類:

public class MyTimerListener implements ServletContextListener {<span style="white-space:pre"></span>private BugXmlTimer  mytimer = new BugXmlTimer  ();    public void contextInitialized(ServletContextEvent event) {        mytimer.timerStart();    }    public void contextDestroyed(ServletContextEvent event) {        mytimer.timerStop();    }    }


最後不要忘了配置web.xml的listener節點:

<listener>    <listener-class>com.TimeListener.MyTimerListener</listener-class></listener>





著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

去哪網實習總結:開發定時任務(JavaWeb)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.