Java.util.Timer 类

java.util.Timer.cancel() 方法用于终止给定的计时器,丢弃任何当前计划的任务。

语法

public void cancel()

参数

无需参数。

返回值

void 类型。

异常

无。

示例:

在下面的示例中,java.util.Timer.cancel() 方法用于终止给定的计时器。

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //创建定时器
    Timer timer = new Timer();

    //创建一个定时器任务
    TimerTask tt = new TimerTask() {
      public void run() {
        for (int i = 0; i <= 10; i++) {
          System.out.println("Working on the task.");
          if(i==5) {
            System.out.println("Stop the task.");
            timer.cancel();
            break;
          }
        }
      };
    };
    
    //调度要执行的任务
    //延迟100毫秒后
    timer.schedule(tt, 100);
  }
}

上述代码的输出将是:

Working on the task.
Working on the task.
Working on the task.
Working on the task.
Working on the task.
Working on the task.
Stop the task.