Question

Well i cant seem to get the scheduled timer to stop/cancel :( if anyone knows how please help me :D

/*Here follows the code */

private void jToggleButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                               
        Timer timer = new Timer();
        if (jToggleButton1.isSelected()) {
            jToggleButton1.setText("STOP");
            jToggleButton1.setBackground(Color.red);
            System.out.println("is called");
            timer.schedule(new TimerTask() {
               @Override
                public void run() {
                    // Your database code here
                    System.out.println("scheduled time reached");
                }
            }, times * 1000);
        } else {
            jToggleButton1.setText("START");
            jToggleButton1.setBackground(Color.green);
            set = false;
            System.out.println("i called it");
            timer.cancel(); //?????this doesnt seem to work :(
        }
    }  
Was it helpful?

Solution

You state:

The problem is what you just mentioned about the timer, i want to stop the current tasks that are running

As per the java.util.Timer API, calling cancel() on the Timer object stops it from creating new future tasks, but does not stop the currently running tasks. So since this is your problem, it's no surprise that cancel() does not help you.

The solution? That lies in the TimerTasks that you're creating. If this were my code, I'd create a class that extends TimerTask, that has a clean way of stopping it, perhaps give it a cancel() method, keep a collection of active running instances of these, and then call cancel() when desired.

A caveat, it can be dangerous to use java.util.Timer in Swing applications without care. If your tasks involve making Swing calls, you will need to take care to make your Swing calls on the Swing event thread. If not, and if all the tasks do are database actions, then you're OK.

As an aside, if you use a ScheduledExecutorService, you can fill it with either Runnables or Callables. The schedule(...) or scheduleAtFixedRate(...) method returns a ScheduledFuture that you can call cancel() on. I think that this works by calling Thread.interrupt() on the task. And so if you go this route, your task should be interruptable and should be able to smoothly handle InterruptedException.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top