Schedule Task in Java using Timer and TimerTask


Java provide simple alternate to schedule any task using the Timer and Timer task similar work like setTimeout and setInterval, However one must not mistake to misunderstand the power of Java, this simple tutorial will make it easy to understand the concept, have a good read..

You might have used the setTimeout and setInterval in javascript if you are one of the web developer who also love java. Now the question is, do Java with its huge API collections provide something like that? Well, guys who love Java will think its nonsense to even ask this, Of course Java has solution. This is what I thought when I come across such a need while working on a software.

Let's take it other way, We have threading in Java so why would I need such a thing like setTimeout or SetInterval? Again, this is what came into my mind but I needed it anyway because I already had several threads in function and I wanted something that will not Increase my threading complexity. So, I come across Java's "Timer" and "TimerTask" class.

These also work by creating a thread and you'll see the structure and function is quite similar but, it took off the overload to take care of another thread. I am going to demonstrate two version which may prove like well known javascript setInterval and setTimeout.

Look at the following code snippet and its result and I'll describe the way they work.


import java.util.TimerTask;
import java.util.Timer;
public class Test extends TimerTask{
    public void run(){
        System.out.println("time up! ");
        System.exit(0);
    }
    public static void main(String...args){
        Test t = new Test();
        new Timer().schedule(t, 5*1000);
        System.out.println("Timer Started");
    }
}

run:
Timer Started
time up! 
BUILD SUCCESSFUL (total time: 5 seconds)

The Timer is present in util as well as swing so its up to you which one you want to use both serve the same purpose in different situation and different manner.

Basically Timer object is needed to invoke the method to call the TimerTask which defines the task we want to do on that Timer.

I have created a Test class which inherits the properties of TimerTask because if you'll see the documentation you'll find that the TimerTask constructor is protected.

There is not much in TimerTask to explore, beside the constructor there are only three methods. which you can look at here.

Anyway, What you want to do is defined in run method. remember run from the Runnable or Thread ?
yeah, the same run with same signature.
Whatever you want to do, just write the code in here. Now in demo program I have used the main method to demonstrate the purpose, but in real life case you would like to make an inner class to do the same.

I want to call run which is defined in the Test class so I need the object of test class. And Timer provide the function to invoke the functionality of TimerTask so I needed a Timer object.

Now now, please pay attention !
I am using schedule() from Timer class.
it takes two parameters


public void schedule(TimerTask, long);

This will call the run function defined in the Test class, Remember the "is a" rule in Inheritance? yes that I used here, because we are passing Test class object instead of TimerTask.

And this will Invoke the run method after the delay we specify. As you see in the result Image.

Please note I have used System.exit(0); because the program does not terminate itself after execution, it will keep going on in Idle mode. As I already told you I am going to discuss two cases. So you can see this in following program, you'll notice only one change that is in the call of schedule method, that is


public void scheduleAtFixedRate(TimerTask, long delay, long period);

the parameter one remains the same as described earlier, the period is the time between two executions of the run method and delay is the delay in execution before the execution after the period is complete. see it like this:

wait for "Period" to complete -> wait for delay to pass -> execute -> again wait for period.


import java.util.TimerTask;
import java.util.Timer;
public class Test extends TimerTask{
	public static int count = 0;
    public void run(){
        System.out.println("time up! "+ ++count);
		if(count==5){
			System.exit(0);
		}
    }
    public static void main(String...args){
        Test t = new Test();
        new Timer().scheduleAtFixedRate(t,10, 5*1000);
        System.out.println("Timer Started");
    }
}

run:
Timer Started
time up! 1
time up! 2
time up! 3
time up! 4
time up! 5
BUILD SUCCESSFUL (total time: 8 seconds)

Reference:

Timer,

TimerTask