Timer has two modes for executing tasks. The most commonly used is schedule, which can execute tasks in two ways: 1: at a certain time (Data), 2: after a fixed time (int delay). These two You can specify the frequency of task execution in any of the following ways. Let’s look at a simple example:
Copy the code code as follows:
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); //Execute this task after 1 second, with an interval of 2 seconds each time. If you pass a Data parameter, you can execute this task at a fixed time.
while(true){//This is used to stop this task, otherwise it will continue to execute this task in a loop
try {
int ch = System.in.read();
if(ch-'c'==0){
timer.cancel();//Use this method to exit the 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("________");
}
}
}
If you are using JDK 5+, there is also a scheduleAtFixedRate mode available. In this mode, the Timer will try its best to run the task at a fixed frequency. For example: In the above example, we want MyTask to run at a fixed frequency. After 1 second, it will be executed every two seconds. However, because java is not real-time (in fact, java’s real-time performance is very poor...), the original meaning we expressed in the previous program cannot be strictly executed. If we call scheduleAtFixedRate, then Timer will try to keep the execution frequency of your Task at every 2 seconds. Run the above program, assuming that scheduleAtFixedRate is used, then the following scenario is possible: After 1 second, MyTask Executed once, because the system is busy, MyTask can be executed a second time after 2.5 seconds. Then, Timer records this delay and tries to make up for this delay in the next task. Then, after 1.5 seconds, MyTask will be executed. Three times. "Execute a task at a fixed frequency rather than a fixed delay time"
Here is a more complicated example, which tells you how to exit a single TimerTask and how to exit all Tasks.
Copy the code code as follows:
package MyTimerTest;
import java.io.IOException;
import java.util.Timer;
/*
* This class gives the main methods of using Timer and TimerTaske, including customizing tasks and adding tasks
* Exit the task and exit the timer.
* Because the status field of TimerTask is accessible at the package level, there is no way to access it outside the java.util. package.
* Obtain its status, which causes some inconvenience to programming. We cannot judge the status of a certain Task.
*
*/
public class TimerTest {
public static void main(String[] args) {
Timer timer = new Timer();
MyTask myTask1 = new MyTask();
MyTask myTask2 = new MyTask();
myTask2.setInfo("myTask-2");
timer.schedule(myTask1, 1000, 2000);
timer.scheduleAtFixedRate(myTask2, 2000, 3000);
while (true) {
try {
byte[] info = new byte[1024];
int len = System.in.read(info);
String strInfo = new String(info, 0, len, "GBK");//Read information from the console
if (strInfo.charAt(strInfo.length() - 1) == ' ') {
strInfo = strInfo.substring(0, strInfo.length() - 2);
}
if (strInfo.startsWith("Cancel-1")) { myTask1.cancel();//Exit a single task
//In fact, it should be judged here whether myTask2 has also exited. If so, it should break. But because it cannot be obtained outside the package
//The status of myTask2, so no judgment can be made here on whether to exit the loop.
} else if (strInfo.startsWith("Cancel-2")) {
myTask2.cancel();
} else if (strInfo.startsWith("Cancel-All")) {
timer.cancel();//Exit Timer
break;
} else {
// Only make judgments on myTask1, be lazy ^_^
myTask1.setInfo(strInfo);
}
} catch (IOException e) { // TODO Auto-generated catch block
e.printStackTrace();
}
}
}
static class MyTask extends java.util.TimerTask {
String info = "^_^";
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println(info);
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
}
}