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.

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
5 Comment threads
2 Thread replies
1 Followers
 
Most reacted comment
Hottest comment thread
5 Comment authors
AlvaroJuhiAbOgulcanMelvyn posted an update Recent comment authors
newest oldest most voted
Ogulcan
Guest
Ogulcan

HOW TO MAKE IT STOP HELP

Ab
Guest
Ab

call cancel() on the Timer instance

Ogulcan
Guest
Ogulcan

Thank you!

Alvaro
Guest
Alvaro

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

Juhi
Guest
Juhi

also u can get example for running task regularly… http://www.javadiscover.blogspot.in/2015/05/java-timer.html

Melvyn posted an update
Guest
Melvyn posted an update

I had been wondering if your web hosting is OK? Not that I’m complaining, but sluggish loading instances times will very frequently affect your placement in google and can damage your high quality score if advertising and marketing with Adwords. Melvyn posted an update http://www.sandbao.com/forum.php?mod=viewthread&tid=89810

trackback
Spring + JDK Timer scheduler example | Spring

[…] + JDK Timer scheduler example Written on April 2, 2010 at 6:33 am by mkyong Learn the JDK Timer scheduler example without Spring and compare the different with this […]