The Java timer uses the Timer class timer in the Java.util package. When used, instantiate and then use the schedule (timertask task, long delay) method of the instance to set the specified task tasks to run after the specified delayed delay. Timer Task Class TimerTask is an abstract class that inherits and overrides its run () method to implement detailed tasks.
Schedule (timertask task, Date time) sets the task to run at a specified time.
The Cancel () method ends the timer.
The schedule (timertask task, long delay, long period) method specifies that task tasks perform a fixed-delay peroid operation after specifying a delayed delay.
The Scheduleatfixedrate (timertask task, long delay, long period) method sets the specified task tasks to run at a fixed frequency peroid after the delay is specified.
To implement a timed task, using the timer and TimerTask classes in Java makes it easy to implement real-time call handling functions. These two classes are convenient to use and can complete most of the needs of our timers.
Look at a simple example:
Import java.io.IOException;
Import Java.util.Timer;
public class Timertest {
public static void Main (string[] args) {
Timer timer = new timer ();
Timer.schedule (New MyTask (), 1000, 2000);//Run this task in 1 seconds, 2 seconds at a time, assuming that a data parameter is passed to run the task at a fixed time.
while (true) {//This is used to stop this task, otherwise the task has been run cyclically.
try {
int ch = System.in.read ();
if (ch-' C ' ==0) {
Timer.cancel ();//Use this method to exit a task
}
} catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
}
Static class MyTask extends java.util.timertask{
@Override
public void Run () {
TODO auto-generated Method Stub
System.out.println ("________");
}
}
}
Timer usage in Java