I am using java Timer and TimerTask for the scheduling operation. When my schedule task breaks due to some exception the timer it scheduled on will be canceled automatically. This is creating problem when i try to schedule new task om the same timer, it throws "IllegalStateException- Timer already canceled"
It will be great help if any one could tell me how to overcome this problem.
If you want the Timer to continue even if one of the tasks has an exception, you need to catch any exception before it exits the TimerTask's run() method. Here is one way to achieve that:
"I'm not back." - Bill Harding, Twister
Joined: Jul 21, 2005
i am doing exactly the way you mentioned above, but still it is not working. I read in below the article that once the timerTask exits with the error the java timer will set the boolean "newTasksMayBeScheduled = false;". Then onwards this will not allow any other task to be scheduled.
[Deepak]: i am doing exactly the way you mentioned above, but still it is not working. I read in below the article that once the timerTask exits with the error the java timer will set the boolean "newTasksMayBeScheduled = false;". Then onwards this will not allow any other task to be scheduled.
That is correct. You can also see this by looking at the source code tor Timer, or more specifically at teh java.util.TimerThread class defined in the same file as Timer. Look at the run() and mainLoop() methods. Anyway: once a TimerTask exits the run() method with an exception, there is no way to make the Timer work again. Therefore, you must prevent the TimerTask from exiting with an exception. That is the purpose of the SafeTimerTask, to trap the exception. You must use this in place of all other TimerTasks , and you must use it beforethe exception occurs. Once the exception occurs, it's too late.
I suppose another alternative is to replace the Timer with a new Timer. However the new timer won't know anything about all the other TimerTasks that were scheduled in the old Timer. So I think using SafeTimerTask is preferred.
subject: How to avoid IllegalStateExceotion in Timer