The Reminder example uses the first scheme, invoking the cancel method from the timer task s run method. Making the timer thread a daemon wouldn t work, because the program needs to keep running until the timer s task executes. Sometimes, timer threads aren t the only threads that can prevent a program from exiting when expected. For example, if you use the AWT at all even if only to make beeps the AWT automatically creates a nondaemon thread that keeps the program alive. The following modification of Reminder adds beeping, which requires us to also add a call to the System.exit method to make the program exit.
Significant changes are in boldface.
You can find the source code in ReminderBeep.java . Here s an example of using a timer to perform a task once per second. You can find the entire program in AnnoyingBeep.java . When scheduling a task for repeated execution, you should use one of the schedule methods when smoothness is important and a scheduleAtFixedRate method when time synchronization is more important. For example, the AnnoyingBeep program uses the schedule method, which means that the annoying beeps will all be at least 1 second apart.