In this example the author puts the main thread running a timer task to sleep before cancelling the timer task like this:
System.out.println("TimerTask started");
//cancel after sometime
try {
Thread.sleep(120000);
} catch (InterruptedException e) {
e.printStackTrace();
}
timer.cancel();
System.out.println("TimerTask cancelled");
try {
Thread.sleep(30000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
After cancelling the author also puts it to sleep for another 30 seconds. Just curious why this is done? Is it only to show that the timer will still run even though the main thread is sleeping and are the additional 30 seconds added just to allow the timer a chance to cancel itself? Also is there another way to tell the timer to cancel after 120 seconds without putting the main thread to sleep?
Follow up
Great answer - just a follow up question to make sure I understand correctly- if the thread is non daemon and we cancel the first task after 2 minutes using the timer to schedule another task like you showed, will that then stop the main thread (As all tasks that were scheduled are now cancelled)?