Monday, September 30, 2013

Run TimerTask in scheduled, repeated fixed-rate.

Example to trigger scheduled, repeated fixed-rate TimerTask, by calling timer.scheduleAtFixedRate().

Run TimerTask in scheduled, repeated fixed-rate.
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
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(){

            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
                timeTask,   //task to be scheduled
                date_1min,  //First time at which task is to be executed    
                5000);    //repeat period, in milliseconds

1 comment:

  1. 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.
    Cheers, Claus.