First, class overview
A timer is a timer tool that is used to schedule a specified task in a background thread. It can schedule a task to execute once or repeatedly.
TimerTask an abstract class whose subclasses represent a task that can be scheduled by the timer.
Second, the 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*); Use the Timer class to set a scheduled task, 0 refers to 0s to start execution, seconds*1000 means to execute once every seconds seconds
}
class Remindtask extends TimerTask ... {
Public void run () ... {
System.out.println ("Time ' s up!" ); Tasks to be performed on a timed basis
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 only to a single thread;
The timer does not guarantee that the task executes very precisely;
The Timer class is thread-safe.
Timer--timer in Java