简体   繁体   中英

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);
    }
}

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)

Why don't you try something like setting a bool true if you start a timer and only let the other Timers start if it's true or false, depends on how you set them

sth like:

boolean checkTimer = false;

//Start a Timer and set checkTimer = true

if(checkTimer == true)
{
  //Start your other timers here
}
else
{
  //Write message that timer is already running
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM