Use java.util.timer

xiaoxiao2021-03-06  36

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 following code checks if there is a new email every 5 minutes:

Private java.util.Timer Timer; Timer = New Timer; 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 calls a server.checknewmail () method every 5 minutes, and does not need to start the thread. The Timer itself is also multi-threaded synchronization, and multiple threads can share a Timer, and do not need external synchronization code. There are in "The Java Tutorial" in a more complete example: public class AnnoyingBeep {T oolkit toolkit; Timer timer; public AnnoyingBeep () {toolkit = Toolkit.getDefaultToolkit (); 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 This program is ringing every 3 seconds and prints a line of messages every 3 seconds. Circulate 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 easily used as a delayed execution, such as the following code delay specified time (in seconds) to perform an operation. Similar to the delay shutdown function.

转载请注明原文地址:https://www.9cbs.com/read-55636.html

New Post(0)