3

basically what I want to do is to make a Timer that runs a specific TimerTask after x seconds, but then the TimerTask can reschedule the Timer to do the task after y seconds. Example is below, it gives me an error "Exception in thread "Timer-0" java.lang.IllegalStateException: Task already scheduled or cancelled" on line where I try to schedule this task in TimerTask run.

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

public class JavaReminder {

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

    class RemindTask extends TimerTask {
        Timer timer;
        int seconds;
        RemindTask(Timer currentTimer, int sec){
            timer = currentTimer;
            seconds = sec;
        }

        @Override
        public void run() {
            System.out.println("ReminderTask is completed by Java timer");
            timer = new Timer(); 
            timer.schedule(this, seconds*200);
            System.out.println("scheduled");
        }
    }

    public static void main(String args[]) {
        System.out.println("Java timer is about to start");
        JavaReminder reminderBeep = new JavaReminder(2);
        System.out.println("Remindertask is scheduled with Java timer.");
    }
}
user3885166
  • 217
  • 2
  • 11
  • Why are you writing the same line again in run() method? timer = new Timer(); timer.schedule(this, seconds*200); As you are already scheduled your task in constructor that why you are getting java.lang.IllegalStateException. Remove these lines and run it again. – pardeep131085 Jul 28 '14 at 17:52

1 Answers1

4

Use new RemindTask instead of existing one.

It should be

timer.schedule(new RemindTask(timer, seconds), seconds*200);

instead of

timer.schedule(this, seconds*200);
Braj
  • 46,415
  • 5
  • 60
  • 76