Java中實現定時器__Java

來源:互聯網
上載者:User

定時器類Timer在java.util包中。使用時,先執行個體化,然後使用執行個體的schedule(TimerTask task, long delay)方法,設定指定的任務task在指定的延遲delay後執行。定時器任務類TimerTask是抽象類別,繼承並重寫其run()方法,可實現具體任務。

 

schedule(TimerTask task, Date time)設定指定任務task在指定時間time執行。

 

cancel()方法結束這個定時器。

 

schedule(TimerTask task, long delay, long period)方法設定指定任務task在指定延遲delay後進行固定延遲peroid的執行。

 

scheduleAtFixedRate(TimerTask task, long delay, long period)方法設定指定任務task在指定延遲delay後進行固定頻率peroid的執行。

 

要實現一個定時任務,運用java中的Timer和TimerTask類可以非常容易實現即時調用處理函數。這兩個類使用起來非常方便,可以完成我們對定時器的絕大多數需要。


 

看個簡單的例子:根據設定檔設定的時間doXXX

 

設定檔如下:time.properties

#delay執行任務前的延遲時間
#internal執行各後續任務之間的時間間隔
delay=1
internal=3

 

代碼如下:
/** * 定時器 * @author zhoucan * */ public class Time { private Timer timer; public Time() { timer = new Timer(); } private TimerTask task = new TimerTask() { public void run() { //doXXX System.out.println("do me"); } }; /** * 啟動定時器 */ public void start() { InputStream is = this.getClass().getResourceAsStream("/time.properties"); Properties pro = new Properties(); try { pro.load(is); } catch (IOException e) { e.printStackTrace(); System.out.println("讀取設定檔失敗!"); } int delay = Integer.parseInt(pro.getProperty("delay")); int internal = Integer.parseInt(pro.getProperty("internal")); timer.schedule(task, delay*1000,internal*1000); } public static void main(String[] args) { Time time = new Time(); time.start(); } }

聯繫我們

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