-1

I've tried Timer and TimerTask and they don't seem to support rescheduling

Here's the code that runs the timer, the start method is called and throws a non-descriptive exception

import java.util.Date;
import java.util.Timer;

public class ClassExecutingTask {

    long delay = readSettings()*1000; // Delay in milliseconds
    Program task = new Program();
    Timer timer = new Timer("timer");
    
    // Read delay in seconds from the settings file
    public int readSettings() {
        return new Program().readSettings();
    }
    
    public void start() {
        timer.cancel();
    
        // Make new timer
        timer = new Timer("timer");
        delay = readSettings()*1000; // Delay in milliseconds
        Date executionDate = new Date();
        timer.scheduleAtFixedRate(task, executionDate, delay);
    }
}

I also tried using ScheduledThreadPoolExecutor, but ended up getting the following stacktrace which makes itself quite clear

Exception in thread "AWT-EventQueue-0" java.lang.IllegalStateException: Task already scheduled or cancelled
    at java.util.Timer.sched(Unknown Source)
    at java.util.Timer.schedule(Unknown Source)
Butterscotch
  • 100
  • 11

1 Answers1

0

You say Timer doesn't work but you didn't provide the code so there's no way to tell what was causing your errors. I'll show you how my working Timer looks.

// Here's an action that will be called every timer event
public class MyTimerAction extends AbstractAction {

    // You may need a target here to access the actual
    // method you wish to invoke.
    // ...

    @Override
    public void actionPerformed(ActionEvent e) {
        // code to be performed
    }
}

// Here's the Timer class 
public class MyTimer extends Timer {

    // The action invoked by the timer.
    private MyTimerAction action;

    public MyTimer(int delay, ActionListener listener) {
        super(delay, listener);
        action = (MyTimerAction)listener;
        //...
    }
}

That should work in terms of a timer. You'll have to make the appropriate changes to work for your scenario.

ChiefTwoPencils
  • 13,548
  • 8
  • 49
  • 75