1

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);
    }
}
4
  • where are you stopping the timer once scheduled? Commented Jun 28, 2014 at 19:20
  • i do not want to stop the timer. I want the 1st timer to be running always. Other timers calls should not be triggered at all. Commented Jun 28, 2014 at 19:26
  • can you explain a bit more how are you running multiple task? Commented Jun 28, 2014 at 19:26
  • Where is the problem with "remembering" that one Timer has already been started so that other tries to start it can be skipped? If wildly different classes start this timer, you'll have to create a service all of them can call, and this service skips multiple start commands. Commented Jun 28, 2014 at 19:28

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks all. Solved the problem by adding the timer class in servlet context listener and it invoked on server start.
Sounds Good. If the issue is resolved then close the thread. Visit stackoverflow tour
1

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.