1. Overview
Perform specific tasks on a regular basis. 2. Classes and Methods 2.1Timer
Java.util.Timer
A timer corresponds to a thread. A timer can schedule multiple tasks. If a task has an exception, the timer thread may not work properly, and other tasks are implicated. It is generally used to schedule lightweight tasks.
Java.util.timer#schedule (java.util.TimerTask task, java.util.Date when)
Perform a task at a specific time.
Java.util.timer#scheduleatfixedrate (timertask task, Date when, long period)
A task is executed every period, starting at a specific time.
2.2 TimerTask
Java.util.TimerTask
Abstract class, which implements the Runnable interface.
Java.util.timertask#cancel ()
Cancels the timed task.
Note: Used TimerTask is like worn socks, no way to be timer dispatch. TimerTask, which have been schedule or cancel, belong to the used TimerTask.
3. Sample Code
Common steps to see below.
1. Create a Class A that inherits from the TimerTask class and rewrite the run () method.
2. Create a Timer object, call the schedule () method, and pass the object of the custom Class A as an argument.
Import Java.util.Timer;
Class Timertasktest extends TimerTask {
@Override public
void Run () {
System.out.println ("3 seconds to say hi");
}
}
public class Timerdemo {public
static void Main (string[] args) {
Timer timer = new timer ();
void Java.util.Timer.schedule (timertask task, long delay, long period)
//delay time after period () every Task.run time interval () The function time unit is millisecond
timer.schedule (New Timertasktest (), 0, 3000)
;
}
* * * 3 seconds say hi
* 3 seconds once say hi *
3 seconds say hi *
3 seconds say hi
* ...
*/