bircastri
bircastri

Reputation: 2165

How can I stop the Thread in Java?

I want to start a Thread (in Java). This Thread should be to execute every 5 minutes. This Thread, start the method, if the method return true, I want to stop the Thread. I'm not able to do this. This is my code:

Timer timer = new Timer(); 
timer.schedule( new TimerTask() 
{ 
    public void run() { 
     verificaAssistenza ass = new verificaAssistenza();
     if(ass.checkAssistenza())
     //I WANT TO STOP THE THREAD
    } 
}, 0, 60*(1000*1));

Upvotes: 0

Views: 72

Answers (2)

Use:

timer.cancel();
timer.purge();

the Doc from Oracle:

cancel() Terminates this timer, discarding any currently scheduled tasks.

and

purge() Removes all cancelled tasks from this timer's task queue.

Upvotes: 1

wero
wero

Reputation: 32980

Just cancel the TimerTask

if (ass.checkAssistenza()) {
    cancel();
    return;
}

From the Javadoc:

Cancels this timer task. If the task has been scheduled for one-time execution and has not yet run, or has not yet been scheduled, it will never run. If the task has been scheduled for repeated execution, it will never run again. (If the task is running when this call occurs, the task will run to completion, but will never run again.)

If the Timer has only one timerTask call cancel on the Timer itself:

final Timer timer = new Timer(); 

    ...
    if (ass.checkAssistenza()) {
        timer.cancel();
        return;
    }

Upvotes: 4

Related Questions