In this example, the main program waits for a second (with Thread.sleep()) while the tasks is scheduled, so we will see the output running, and after that second, the process stops, but not exits because the Timer is still active. We can write “timer.cancel()”, the task is cancelling too and the program exists.

The problem comes when resumin this task after a while, because we have to create the TimerTask object again, if we try to reuse the old TimerTask (task) created, we’ll get an exception.

But, as we must define the inner TimerTask class again, it’s interesting to create a separate derivate class. But let’s go further, we’ll make a TimerTask derivate that cancels and resumes itself, so our TimerTask (MyTimerTask) must know the Timer object, this way it can also re-schedule the task at different frequencies:

But, as we can see, we must re-create the task object when re-scheduling, what about passing information between the old task to the new task? We may want that, for example, to know what has happened before the new task is created. To do that, we can create a store class, where we can use the attributes to store useful information between schedules, and we can pass this variable to our MyTimerTask constructor, but to avoid external classes to modify the values of our store class, this new overloaded constructor can be private.

In the next example, we just store an integer (we can store as many things as we want), and with this object we will control the times the task was canceled, and make it exit after 5 times:
MyTimerTaskInfo.java