Reputation: 49
I have a question about the class java.util.Timer, specifically its cancel()
method.
If I write code like this and call it 4000 times (for example), it won't stop executing, event it should I guess:
Timer timer = new Timer();
timer.schedule(new TimerTask() {
private int id = ++TimerTest.counter;
@Override
public void run() {
if(counter % 100 == 0)
System.out.println("TimerTest #" + id + "\nI'm doing task: " + task);
if(counter == 4000 && canceled == true){
System.out.println("Canceling...");
timer.cancel();
}
}
}, 0);
But instead of above script, I can change it to:
Timer timer = new Timer();
timer.schedule(new TimerTask() {
private int id = ++TimerTest.counter;
@Override
public void run() {
if(counter % 100 == 0)
System.out.println("TimerTest #" + id + "\nI'm doing task: " + task);
if(counter == 4000 && canceled == true){
System.out.println("Canceling...");
}
}
}, 0);
timer.cancel();
I was looking for the same problem description but I didn't come across anything special :)
Upvotes: 0
Views: 266
Reputation: 1219
The problem appears to be in that you appear to be calling the Timer 4000 times. Instead you should have 1 Timer and schedule a period with it. Call the
public void schedule(TimerTask task, long delay, long period)
Method instead of
public void schedule(TimerTask task, long delay)
Here is an example of it being used correctly:
import java.util.Timer;
import java.util.TimerTask;
public class TimerTest {
private static int counter = 0;
private void doTimer() throws InterruptedException {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
counter ++;
System.out.println("TimerTest #" + counter + " I'm doing task");
}
}, 0,1000);
//Sleep for 10 seconds before cancelling the timer
Thread.currentThread().sleep(10000);
System.out.println("Timer cancelled");
timer.cancel();
}
public static void main(String args[]) throws InterruptedException {
new TimerTest().doTimer();
}
}
This stops the Timer after 10 seconds:
TimerTest #1 I'm doing task
TimerTest #2 I'm doing task
TimerTest #3 I'm doing task
TimerTest #4 I'm doing task
TimerTest #5 I'm doing task
TimerTest #6 I'm doing task
TimerTest #7 I'm doing task
TimerTest #8 I'm doing task
TimerTest #9 I'm doing task
TimerTest #10 I'm doing task
Timer cancelled
Upvotes: 1