Timer與TimerTask應用。利用 timer.schedule(new RemindTask() , now, minutes * 2 * 1000),來實現從程式啟動後每隔幾秒鐘執行一次應用程式,並限定執行幾次後程式自動停止,範例如下:
package testjava;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class EggTimer {
private final Timer timer = new Timer();
private final int minutes;
public EggTimer(int minutes) {
this.minutes = minutes;
}
public void start() {
Date now = new Date();
timer.schedule(new RemindTask() , now, minutes * 2 * 1000);
}
class RemindTask extends TimerTask {
int runtimer= 10;
public void run(){
if (runtimer> 0){
System.out.println(runtimer+":Beep! "+ new java.util.Date());
runtimer--;
} else{
System.out.println(runtimer+" Time''s up!! "+ new java.util.Date());
timer.cancel(); //call System.exit is the same to stop PGM
//System.exit(0); //Stops the AWT thread (and everything else)
}
}
}
public static void main(String[] args) throws Exception {
System.out.println("開始時間:" + new java.util.Date());
EggTimer eggTimer = new EggTimer(1);
eggTimer.start();
}
}
***********************************************************************
範例二 : 每週日午夜零時執行一次
/* class MainApplication */
package sche.*;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class MainApplication {
public static void main(String[] args) {
Timer timer = new Timer();
Calendar date = Calendar.getInstance();
date.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
date.set(Calendar.HOUR, 0);
date.set(Calendar.MINUTE, 0);
date.set(Calendar.SECOND, 0);
date.set(Calendar.MILLISECOND, 0);
// 每週日午夜零時執行一次
timer.schedule(new ReportGenerator(),date.getTime(),1000 * 60 * 60 * 24 * 7);
}
留言列表