Skip to content
Advertisement

TimerTask class has to run only once in java

I have a class that runs for every 10 secs, but when I execute it more than once, multiple timers are started. If one timer is already running, I want the other timer calls to be ignored. I want only one timer to be running at a given point of time. Please help.

My code:

import java.util.Timer;
import java.util.TimerTask;
public class Test1 extends TimerTask{
    @Override
    public void run() {
            System.out.println("In run method");
        }

    public static void main(String args[]) {
        System.out.println("In main method");
        Timer timer= new Timer();
        timer.schedule(new Test1(), 10000,10000);
    }
}

Advertisement

Answer

I want the 1st timer to be running always. Other timers calls should not be triggered at all.

Try with Singleton patten that allows only single instance of the class.

Sample code:

public class Test extends TimerTask {    
    private static Test instance = new Test();

    private Test() {}    
    public static Test getInstance() {
        return instance;
    }

    @Override
    public void run() {
        System.out.println("In run method");
    }
}

Now if you try to start another Task on the same instance it will result in below exception:

java.lang.IllegalStateException: Task already scheduled or cancelled
at java.util.Timer.sched(Unknown Source)
at java.util.Timer.schedule(Unknown Source)
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement