In application development, periodic operations are often required, such as checking new emails every five minutes. The most convenient and efficient way to implement such operations is to use the java. util. Timer tool class. For example, the following code checks whether there are new emails every five minutes:
Private java. util. Timer timer;
Timer = new timer (true );
Timer. Schedule (
New java. util. timertask () {public void run () {// server. checknewmail (); check new emails}, 0, 5*60*1000 );
After using these lines of code, Timer itself will call the server. checknewmail () method every five minutes without starting the thread. Timer itself is also multi-threaded synchronization. Multiple Threads can share one timer without external synchronization code.
A more complete example is provided in the Java Tutorial:
Public class annoyingbeep {T
Oolkit toolkit;
Timer timer;
Public annoyingbeep (){
Toolkit = toolkit. getdefatooltoolkit ();
Timer = new timer ();
Timer. Schedule (New remindtask (), 0, // initial delay 1*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. Exit System. Exit (0 );
// Stops the AWT thread (and everything else)
}
}
}
...
}
This program calls a bell every three seconds and prints a message. Loop 3 times. The program output is as follows:
Task scheduled.
Beep!
Beep! // One second after the first beep
Beep! // One second after the second beep
Time's up! // One second after the third beep
The timer class can also be conveniently used for delayed execution. For example, the following code delays a specified time (in seconds) to execute an operation. Similar to the delayed shutdown function of TV.
... Public class reminderbeep {
... Public reminderbeep (INT seconds ){
Toolkit = toolkit. getdefatooltoolkit ();
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. Exit System. Exit (0 );
// Stops the AWT thread (and everything else)
}
}
...
}
}