So I'm running a Java server and in one class I have a static Timer. Then I have another class which has many instances being created and destroyed throughout the life of the program, each with their own TimerTask (using the static Timer). When an instance is destroyed, it calls cancel() on the TimerTask.
The problem is, I'm not sure if this is good design, and also I get errors sometimes when the instance is creating and scheduling its TimerTask:
java.lang.IllegalStateException: Timer already cancelled.
Here is some code to show what I mean.
/**
* Starts scheduled tasks using TimerTask
*/
private void initTasks()
{
// room heartbeat thread: start immediately, run once every second
roomHeartbeatTask = new RoomHeartbeatTask(this);
RoomListExtension.roomHeartbeat.schedule(roomHeartbeatTask, 0, 1000);
// add additional tasks here
}
/**
* Cancels all tasks that have been started by this extension
*/
private void cancelTasks()
{
roomHeartbeatTask.cancel();
}