In application development, some periodic operations often need, such as checking new emails every 5 minutes. For such operations, the most convenient, efficient implementation is to use the Java.util.TiMer tool class. For example, the code below checks if there is a new email every 5 minutes: private java.util.timer Timer; timer = new time (true); timer.schedule (new java.util.timertask () {public void Run () {/ /server.checknewmail (); check new mail}}, 0, 5 * 60 * 1000) After using these lines of code, Timer itself will call a server.checknewmail () method every 5 minutes, do not need to start threads yourself . The Timer itself is also multi-threaded synchronization, and multiple threads can share a Timer, and do not need external synchronization code. There is a more complete example in "The Javatutorial": public class AnnoyingBeep {Toolkit Toolkit; TIMER TIMER;
Public AnnoyingBeep () {Toolkit = Toolkit.getDefaultToolkit (); Timer = new timer (); timer.schedule (new remindtask (), 0, // initial delay1 * 1000); // subsequent rate}
Class Remindtask EXTENDS TIMERTASK {Int NumWarningBeeps = 3;
Public void Run () {if (NumWarningBeeps> 0) {Toolkit.beep (); System.out.Println ("Beep!"); NumWarningBeeps -;} else {Toolkit.beep (); System.out.println "Time's UP!"); // Timer.Cancel (); // Not Necessary Because We call system.exitsystem.exit (0); // stops the a'}}}} ...
} This program is ringing every 3 seconds and printed a line of messages. Circulate 3 times. The program output is as follows: Task Scheduled.beep! Beep! // One second after the first beepbeep! // One second beepbeep! // One Second After The second Beeptime's Up! // One Second After the Third BeepTimer class can also be easily used as a delayed execution, such as The following code delay specifies the time (in seconds) to perform actions. Similar to the delay shutdown function. ...
Public class reminderbeep {... public reminderbeep (int seconds) {Toolkit = Toolkit.getDefaultToolkit (); timer = new timer (); timer.schedule (new remindtask (), seconds * 1000);}
Class Remindtask Extends Timertask {public void Run () {System.out.println ("Time's Up!"); Toolkit.beep (); // Timer.Cancel (); // Not Necessary Because We call system.exitsystem.exit (0); // stops the a'}}} ...}