Dino
Dino

Reputation: 821

Thread is not terminated using conditional TimerTask

I test a simple Timer and TimerTask based on Reminder example from this article.

The only difference is I use conditional if before timer.cancel(). In the original example, the thread stop as expected but in my code, it does not stop. What's wrong?

import java.util.Timer;
import java.util.TimerTask;

public class ConditionalReminder {
    Timer           timer;

    public ConditionalReminder(int seconds) {
        timer = new Timer();
        timer.schedule(new RemindTask(), seconds*1000);
    }

    class RemindTask extends TimerTask {
        int counter;

        public void run() {
            counter++;
            System.out.format("Time's up!%n");
            if(counter==100) 
            {
                timer.cancel(); //should terminate thread
            }
        }
    }

    public static void main(String args[]) {
        new ConditionalReminder(2);
        System.out.format("Task scheduled.%n");
    }
}

Upvotes: 0

Views: 79

Answers (1)

shmosel
shmosel

Reputation: 50716

Timer.schedule(TimerTask, long) schedules a task to execute once, after the provided delay. If you want it to repeat, you'll need to use Timer.schedule(TimerTask, long, long). For example:

int delay = 0;
int interval = seconds * 1000;
timer.schedule(new RemindTask(), delay, interval);

Upvotes: 2

Related Questions