Timed tasks: Using timer and TimerTask in Java
The Java.util.Timer timer is actually a thread that is scheduled to be owned by the Timertasks.
A timertask is actually a class that has a run method, and the code that needs to be executed regularly is put into the Run method body, and timertask is typically created in the form of an anonymous class.
A complete timer:
Java.util.Timer Timer = new Java.util.Timer (true);
True indicates that the timer runs in daemon mode (Low priority,
Program End timer also end automatically), note that javax.swing
There is also a timer class in the package, if you use the Swing package in import,
Pay attention to the clash of names.
TimerTask task = new TimerTask () {
public void Run () {
...//each time the code needs to be executed is put into this area.
}
};
Here are a few ways to schedule a task:
Timer.schedule (task, time);
Time is a date type: Executed once at the specified times.
Timer.schedule (Task, firsttime, period);
Firsttime is a date type and period is a long
This is done every period milliseconds from the firsttime moment.
Timer.schedule (task, delay)
Delay is a long type: it is executed once from now through delay milliseconds
Timer.schedule (task, delay, period)
Delay is long,period to long: From now on delay milliseconds, every period
Milliseconds to execute once.
Here is a complete example, consisting of two classes, a custom task, a call to Java.util.Timer
Custom tasks:
Import Java.util.Timer; public class Timertasktest extends java.util.timertask{@Override public void Run () {//TODO Auto -generated method Stub System.out.println ("Start"); } }
2. Call Java.util.Timer
Import Java.util.Timer; public class Test {public static void main (string[] args) {Timer timer = new timer (); Timer.schedule (New Timertasktest (), 1000, 2000); } }
According to the above description, you can execute the program every 2 seconds after 1 seconds.
Timed tasks: Using timer and TimerTask in Java