java中伺服器啟動時,執行定時任務

來源:互聯網
上載者:User

標籤:時間   logger   實現   new   ted   nal   code   ogg   pack   

package com.ripsoft.util;import java.util.Calendar;import java.util.Timer;import javax.servlet.ServletContextEvent;import javax.servlet.ServletContextListener;public class TimerListener implements ServletContextListener{    private Timer timer = null;            @Override      public void contextInitialized(ServletContextEvent event) {          timer = new Timer(true);          event.getServletContext().log("定時器已啟動");               //設定執行時間        Calendar calendar = Calendar.getInstance();        int year = calendar.get(Calendar.YEAR);        int month = calendar.get(Calendar.MONTH);        int day = calendar.get(Calendar.DAY_OF_MONTH);//每天        //定製每天的11:00:00執行        calendar.set(year, month, day, 11, 00, 00);        java.util.Date date = calendar.getTime();        int period = 30 * 1000;        //每天的date時刻執行TestTask,每隔30秒重複執行        timer.schedule(new TestTask(), date, period);        //每天的date時刻執行TestTask, 僅執行一次        //timer.schedule(new TestTask(), date);    }        @Override      public void contextDestroyed(ServletContextEvent event) {          if (timer != null) {              timer.cancel();              event.getServletContext().log("定時器銷毀");          }      }  }
package com.ripsoft.util;import java.util.TimerTask;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;public class TestTask extends TimerTask{    protected final Log logger = LogFactory.getLog(getClass());            private static boolean isRunning = false;        @Override      public void run() {          if (!isRunning) {              isRunning = true;              logger.info("開始執行任務。");                int i = 0;              while (i++ < 10) {                  logger.info("已完成任務的" + i + "/" + 10);              }                isRunning = false;              logger.info("任務執行結束。");            } else {              logger.info("上一次任務執行還未結束,本次任務不能執行。");          }        }  }

1.TestTimerListener.java執行定時任務,實現servlet的ServletContextListener介面,當伺服器啟動時開始執行TestTask任務

2.想要任務在伺服器啟動時定時執行,就要藉助監聽實現需要在web.xml中做如下配置

    <listener>        <listener-class>com.ripsoft.util.TimerListener</listener-class>    </listener>

java中伺服器啟動時,執行定時任務

聯繫我們

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