Can a Java static timer handle multiple TimerTasks calling cancel ()?

So, I start the Java server, and in one class I have a static timer. Then I have another class that has many instances that are created and destroyed throughout the entire program life cycle, each with its own TimerTask (using a static timer). When an instance is destroyed, it calls cancel () in TimerTask.

The problem is that I'm not sure if this is a good design, and sometimes errors occur when an instance creates and configures 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();
}
+3
source share
1 answer

, cancel(), Timer "", .

API:

, , .

:

  • Timer Timer . , , Timer, TimerTask s. .
  • Timer, (, ArrayList<TimerTask>) . , , Timer, ( , ). , TimerTask (, , "" ).
  • Timer -like, TimerTask s. (, - , )
  • ScheduledThreadPoolExecutor, .
+5

Source: https://habr.com/ru/post/1758831/


All Articles