標籤: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