Timer in java -- timer, java Timer timer
I. Category Overview
Timer is a Timer tool used to schedule the execution of specified tasks in a background thread. It can plan to execute a task once or repeatedly.
TimerTask is an abstract class. Its subclass represents a task that can be scheduled by Timer.
Ii. code example
Import java. util. Timer;
Import java. util. TimerTask;
Public class Reminder ...{
Timer timer;
Public Reminder (int seconds )...{
Timer = new Timer ();
Timer. schedule (new RemindTask (), 0, seconds * 1000); // use the Timer class to set a scheduled task to be executed. 0 indicates that the task starts to be executed after 0 s, and seconds * 1000 indicates that the task is executed every seconds second.
}
Class RemindTask extends TimerTask ...{
Public void run ()...{
System. out. println ("Time's up! "); // The task to be periodically executed
Timer. cancel (); // Terminate the timer thread
}
}
Public static void main (String args [])... {
System. out. println ("About to schedule task .");
New Reminder (5 );
System. out. println ("Task scheduled .");
}
}
Note::
Each Timer corresponds to only one thread;
Timer does not guarantee that the task execution is very accurate;
The Timer class is thread-safe.