1. Introduction

Java.util. TimerTask is a task that is executed by the Timer class. Inherit the Runnable interface

2. Class variables

There are four states:

    int state = VIRGIN;

    static final int VIRGIN = 0;

    static final int SCHEDULED   = 1;

    static final int EXECUTED    = 2;

    static final int CANCELLED   = 3;
Copy the code

VIRGIN: The task has not been executed

SCHEDULED: A task has been SCHEDULED (if it is not a recurring task, it has not been executed yet)

EXECUTED: A non-repetitive task has been performed (or is being EXECUTED) and is not cancelled

CANCELLED: Task has been CANCELLED (call timerTask.cancel)

Lock: The lock that controls access to the TimerTask

 final Object lock = new Object();
Copy the code

NextExecutionTime: time when the next task is executed. If the task is repetitive, it is updated before each task is executed

long nextExecutionTime;
Copy the code

Period: indicates the period of a repetitive task. A positive value indicates that the task is executed at a fixed rate, a negative value indicates that the task is executed at a fixed delay, and 0 indicates that the task is not repetitive. The difference between fixed frequency and fixed delay is explained by looking at the code in the Timer

 long period = 0;
Copy the code

3. Membership method

Construction method:

  protected TimerTask(a) {}Copy the code

Run () : indicates the operation that timerTask needs to perform

public abstract void run(a);
Copy the code

Cancel () : Cancels a task. If the task is being executed, the task will be completed.

 public boolean cancel(a) {
        synchronized(lock) {
            boolean result = (state == SCHEDULED);
            state = CANCELLED;
            returnresult; }}Copy the code

ScheduledExecutionTime () : indicates the last execution time

public long scheduledExecutionTime(a) {
        synchronized(lock) {
            return (period < 0? nextExecutionTime + period : nextExecutionTime - period); }}Copy the code