Search code examples
javaswingclasstimertimertask

Is it possible to stop a Timer from a separate class?


I am trying to reset a Timer so as to avoid having multiple instances of it. To achieve this, I want to stop the Timer from a separate class, something like this:

public void Timer() 
{
    Timer timer = new Timer(); 
    long interval = (1000) ;
    timer.schedule( new TimerTask() 
    {
        public void run() 
        {
            // code //       
        }
    }, 0, interval);         
}

public void Stop() 
{
    // stop Timer //
}

I feel this may be achievable by terminating Timer(); if it is not possible to stop the Timer I would much appreciate being shown how I could best go about terminating the class as cleanly as possible. Thank you.


Solution

  • I devised a pretty rudimentary solution:

    boolean stop;
    public void Timer() 
    {
        Timer timer = new Timer(); 
        long interval = (1000) ;
        timer.schedule( new TimerTask() 
        {
            public void run() 
            {
                if condition is met{
                    execute
                }
                else if(stop == true){
                    timer.cancel();
                }       
            }
        }, 0, interval);         
    }
    
    .
    .
    .
    
    stop = true;
    try {
        Thread.sleep(2000);
    } catch (InterruptedException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }
    stop = false;
    Timer1();
    

    Basically, the boolean value stops the Timer, gives it 2 seconds to make sure there is no overlap, and is then set back to false to safely reset the Timer.