Example to trigger scheduled, repeated fixed-rate TimerTask, by calling timer.scheduleAtFixedRate().
|
Run TimerTask in scheduled, repeated fixed-rate. |
package java_time;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
/**
* @web http://java-buddy.blogspot.com/
*/
public class Java_Time {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
Date calendarDate = calendar.getTime();
System.out.println("Now: " + calendarDate);
Calendar cal_1min = Calendar.getInstance();
cal_1min.add(Calendar.MINUTE, 1);
Date date_1min = cal_1min.getTime();
System.out.println("1 min later: " + date_1min);
TimerTask timeTask = new TimerTask(){
@Override
public void run() {
Calendar timerNow = Calendar.getInstance();
Date timerNowDate = timerNow.getTime();
System.out.println("Timer reached: " + timerNowDate);
}
};
Timer timer = new Timer();
//One time only
//timer.schedule(timeTask, date_1min);
//Trigger scheduled, repeated fixed-rate TimerTask
timer.scheduleAtFixedRate(
timeTask, //task to be scheduled
date_1min, //First time at which task is to be executed
5000); //repeat period, in milliseconds
}
}
Thank you very much. This was _exactly_ what I was looking for. Your example is simple and easy to understand, had no problems to implement it. Oracle Doc is pretty good for more details. Hope it will also work in a Java FX8 environment I'm targeting to.
ReplyDeleteCheers, Claus.