Java timertask wont stop when .cancel() is called

45 Views Asked by At

I have the following timer:

Timer timer = new Timer();
TimerTask task = new TimerTask() {
    public void run() {
        intCounter.incrementCount();
        System.out.println(intCounter.counterNum);
    };
};

It runs when the start button is pressed and should stop when the pause button is pressed however it will not stop. Here is the code for my pause button, the text "pressed pause" prints however the timer continues to count.

        if (e.getSource() == pauseButton) {
        System.out.println("pressed pause");
        task.cancel();
        timer.cancel();

EDIT: I have tried modifying my code with an answer posted for a similar question but the result did not change. I changed my TimerTask to look like this:

    Timer timer = new Timer();
TimerTask task = new TimerTask() {
    private volatile Thread thread;

    public void run() {
        thread = Thread.currentThread();
        intCounter.incrementCount();
        System.out.println(intCounter.counterNum);
    }

    public boolean cancel() {
        Thread thread = this.thread;
        if (thread != null) {
            thread.interrupt();
        }
        return super.cancel();
    }
};
1

There are 1 best solutions below

1
queeg On

This is what your task should look like:

TimerTask task = new TimerTask() {
    private boolean cancelled = false;

    public void run() {
        int x = 1000; // so many chunks to work on
        while (x > 0 && !cancelled) {
            // perform one chunk of work
            x--;
        }
    }

    public boolean cancel() {
        cancelled = true;
    }
};