Java定時器:Timer

來源:互聯網
上載者:User

標籤:size   日期   系統   test   exception   lin   doc   text   span   

1. schedule(TimerTask task, Date time):在指定Date日期,開始執行TimerTask裡的run方法
2. schedule(TimerTask task, long delay):延遲一段時間後,開始執行TimerTask裡的run方法

3. schedule(TimerTask task, long delay, long period):延遲一段時間後,開始執行TimerTask裡的run方法,並每隔period秒後,重複執行run方法



1 和 2 執行個體:
package com.timer;import java.util.Date;import java.util.Timer;import java.util.TimerTask;public class Run1 {private static Timer timer = new Timer();/* * TimerTask 的實作類別,並重寫run()方法 */static public class MyTask extends TimerTask{@Overridepublic void run() {System.out.println("運行了!時間為:" + new Date());}}public static void main(String[] args) {try{MyTask task = new MyTask();//timer.schedule(task, 5000);//延遲5秒後,開始執行task裡的run()方法timer.schedule(task, 5000, 2000);//延遲5秒後,開始執行task裡的run()方法,並在後面每隔兩秒重複執行run()方法}catch(Exception e){e.printStackTrace();}}}

  

3 執行個體:

package com.timer;import java.text.SimpleDateFormat;import java.util.Date;import java.util.Timer;import java.util.TimerTask;public class Run1 {private static Timer timer = new Timer();/* * TimerTask 的實作類別,並重寫run()方法 */static public class MyTask extends TimerTask{@Overridepublic void run() {System.out.println("運行了!時間為:" + new Date());}}public static void main(String[] args) {try{MyTask task = new MyTask();SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");String dateString = "2017-10-17 9:45:00";Date dateRef = sdf.parse(dateString);System.out.println("字串時間:" + dateRef.toLocaleString() + "  目前時間:" + new Date().toLocaleString());timer.schedule(task, dateRef);//在指定日期,開始執行run()方法,指定日期要比你現在的系統時間晚}catch(Exception e){e.printStackTrace();}}}

 運行效果

字串時間:2017-10-17 9:45:00  目前時間:2017-10-17 9:44:33運行了!時間為:Tue Oct 17 09:45:00 CST 2017

 

Java定時器:Timer

聯繫我們

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