The Timer and TimerTask classes of java.util tools

JDK8 Online Api Chinese Manual

JDK8 Online Api English Manual

Timer and TimerTask classes

   An interesting and useful feature provided by java.util is the ability to schedule tasks at certain times in the future. The classes that support this feature are Timer and TimerTask. Using these classes, you can create threads that run in the background and wait for specific moments. When the time comes, the task linked to the thread is executed. There are various options that can be used to schedule tasks that are repeatedly executed and run during a specific period. Although you can always manually create tasks that run at specific times using the Thread class, Timer and TimerTask greatly simplify this process.
   Timer and TimerTask can work together. The Timer class is used to schedule tasks. The scheduled task must be an instance of the TimerTask class. Therefore, in order to schedule a task, you must first create a TimerTask object, and then use the Timer instance to schedule the execution of the task.
   TimerTask implements the Runnable interface, so it can be used to create threads for execution. The constructor of TimerTask is as follows:

protected TimerTask()

   Table 1 shows the methods defined by the TimerTask class. Note that the run () method is abstract, which means it must be rewritten. The run () method contains the code to be executed. This method is defined by the Runnable interface. Therefore, the easiest way to create a timed task is to extend the TimerTask class and override the run () method.

Table 1 The methods defined by the TimerTask class
method Description
boolean cancel() Terminate the task. True if the task is successfully blocked, otherwise false
abstract void run() Contains code for scheduled tasks
long scheduledExecutionTime() Returns the time when the scheduled task was last executed

   After creating a task, you can use the Timer class object to schedule the execution of the task. The constructor of the Timer class is as follows:

Timer()
Timer(boolean DThread)
Timer(String tName)
Timer(String tName,boolean DThread)

   The Timer object created in the first version runs as a normal thread. For the second version, if DThread is true, the daemon thread is executed . As long as the rest of the program continues to execute, the daemon thread will execute. The third and fourth versions allow you to specify a name for the Timer thread. Table 2 shows the methods defined by the Timer class.

Table 2 The methods defined by the Timer class
method Description
void cancel() Cancel timer thread
int purge() Delete canceled tasks from scheduled tasks
void schedule(TimerTask TTask,long wait) TTask is scheduled to be executed after the period passed by the parameter wait, the unit of the wait parameter is milliseconds
void schedule(TimerTask TTask,long wait,long repeat) TTask is scheduled to be executed after the period passed by the parameter wait, and then the task is repeatedly executed at the time interval specified by repeat. The unit of the wait and repeat parameters are milliseconds
void schedule(TimerTask TTask,Date targetTime) TTask is scheduled to execute at the time specified by targetTime
void schedule(TimeTask TTask,Date targetTime,long repeat) TTask is scheduled to execute at the time specified by targetTime, and then the task is repeatedly executed at the interval passed by repeat. The unit of the repeat parameter is milliseconds
void scheduleAtFixedRate(TimerTask TTask,long wait,long repeat) TTask is scheduled to be executed after the period passed by the parameter wait, and then the task is repeatedly executed at the time interval specified by repeat. The units of the wait and repeat parameters are milliseconds. The time of each repeated execution is related to the time of the first execution, not the time of the previous execution, so the overall rate of execution is fixed
void scheduleAtFixedRate(TimerTask TTask,Date targetTime,long repeat) TTask is scheduled to execute at the time specified by targetTime, and then the task is repeatedly executed at the interval passed by repeat. The unit of the repeat parameter is milliseconds. The time of each repeated execution is related to the time of the first execution, not the time of the previous execution, so the entire rate of execution is fixed

   After creating the Timer object, you can call the schedule () method on the created Timer object to schedule the task. As shown in Table 2, the schedule () method has many forms, and tasks can be scheduled in multiple ways.
   If you create a non-daemon task, you will want to call the cancel () method to end the task when the program ends. If you do not do this, the program may be suspended for a while.
   The following program demonstrates the Timer and TimerTask classes. The program defines a scheduled task, and the task's run () method will display the message "Timer task executed." This task is scheduled to be executed after an initial delay of one second, and is executed every half a second.

//Demonstrate Timer and TimerTask.
import java.util.TimerTask;
class MyTimerTask extends TimerTask {
    @Override
    public void run() {
        System.out.println("Timer task executed.");
    }
}
import java.util.Timer;
class TTest {
    public static void main(String[] args) {
        MyTimerTask myTask = new MyTimerTask();
        Timer myTimer = new Timer();
        /*Set an initial delay of 1 second,
        then repeat every half second.
         */
        myTimer.schedule(myTask,1000,500);
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        myTimer.cancel();
    }
}
Published 59 original articles · won 20 · views 3634

Guess you like

Origin blog.csdn.net/qq_34896730/article/details/104228535