1
votes

I have scheduled a TimerTask to run at a fixed time with a interval of one day using java.util.Timer.scheduleAtFixedRate(). The TimerTask is having a logic to control the excution for a duration say 6 hours. The timer is suppose to start this task next day same given time. But sometime the task is restarted just as soon as it stops after the duration. I have not seen any pattern of this occurance, it just happens randomly. I have tested this by running this application many times but could not identify any particular pattern.

Its something like this.

class App{
  public static void main(final String[] args) {
    Timer timer = new Timer();
    ProcessManagerTask processManager = new ProcessManagerTask()
    timer.scheduleAtFixedRate(processManager, today @ 01 AM, 1440 minutes))
    //some logic to keep this running forever
  }
}

public class ProcessManagerTask extends TimerTask {
  public ProcessManagerTask(){
    //end time = today @ 7 AM
  }
  public void run() {
    while(end time is not expired){
      //do some stuff
    }
}

The ProcessManagerTask sometime restart immediately at 7 (when the task is over).

EDIT: Guys any idea why the problem appearing for Timer. I am still not able to figure out.

EDIT [08 April 2011]: Guys problem with Timer is still not resolved. I would appreciated if some one can help.

2
I'd recommend using ScheduledExecutorService. - mre
Could there be an issue with something starting the program again? Where is this running? - jzd
I do not understand your query clearly. If you mean OS its running on windows. This app run as windows service but this issue is coming even when I run through command prompt. - Amit
Have you tried noobs suggestion? It was my understanding that the Timer class was designed for small lightweight tasks - what you are describing sounds more heavyweight. If at all possible though, I would recommend the other suggestions of ditching the java timer/scheduler and either putting it in the cron (linux) or as a scheduled task (windows) - it would be trivial to wrap it in a bat/shell script to accomplish this. - tofarr
Thanks @Tofarr for replying. As I have mentioned this in my other comments I cannot switch to cron job or windows scheduler as this is design decision taken by architects as they want the application running all the time and the required process should be controlled within application. - Amit

2 Answers

1
votes

From the docs:

If an execution is delayed for any reason (such as garbage collection or other background activity), two or more executions will occur in rapid succession to "catch up."

Therefore, it would appear that your task was not executed at exactly 1 AM, so was executed twice.

1
votes

Since you are running this on windows. One option is to use a scheduled task to kick off the job every day. A big advantage is that the job will still run even when the machine is restarted. Where as something that is kicked off at the command line will have to be restarted.