Sunday, September 29, 2013

Timer and TimerTask example, execute code in a specified time.

This example implement a TimerTask object. It's run() method will be called in 1 minute later, set with Timer.schedule() method.

Timer and TimerTask example
Timer and TimerTask example

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("1 min Timer reached: " + timerNowDate);
            }
            
        };
        
        Timer timer = new Timer();
        timer.schedule(timeTask, date_1min);
        
    }
}


Next: Run TimerTask in scheduled, repeated fixed-rate.

No comments:

Post a Comment