JDK Timer scheduler example

JDK Timer is a simple scheduler for a specified task for repeated fixed-delay execution. To use this, you have to extends the TimerTask abstract class, override the run() method with your scheduler function.

RunMeTask.java


package com.mkyong.common;

import java.util.TimerTask;

public class RunMeTask extends TimerTask
{
	@Override
	public void run() {
		System.out.println("Run Me ~");
	}
}

Now, you can schedule it by calling the schedule() method of Timer.


public void schedule(TimerTask task,
                     long delay,
                     long period)

App.java


package com.mkyong.common;

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

public class App 
{
    public static void main( String[] args )
    {
    		
    	TimerTask task = new RunMeTask();
    	
    	Timer timer = new Timer();
    	timer.schedule(task, 1000,60000);
    
    }
}

In this example, the timer will print the “Run Me ~” message every 60 seconds, with a 1 second delay for the first time of execution.

6 comments on “JDK Timer scheduler example

  1. is it possible to control this execution when the application is clustered?

    Reply

Leave a Comment

Your email address will not be published. Required fields are marked *