Scheduling a Task at fixed schedule using Timer in Java

Views: 126   

The following code shows you how to schedule a TimerTask at every 2 seconds.

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class TimerTaskExample {
    public static void main(String[] args) {
        Timer t = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                System.out.println("From timer task @" + new Date());  
            }
        };

        t.schedule(task, 0L, 2_000L);
    }
}

Output:

From timer task @Wed May 02 22:25:02 IST 2018
From timer task @Wed May 02 22:25:04 IST 2018
From timer task @Wed May 02 22:25:06 IST 2018
From timer task @Wed May 02 22:25:08 IST 2018
From timer task @Wed May 02 22:25:10 IST 2018
From timer task @Wed May 02 22:25:12 IST 2018
On By