Java.util.Timer 类

java.util.Timer.scheduleAtFixedRate() 方法用于安排指定任务重复固定速率执行,从指定时间开始。随后的执行大约以固定的时间间隔进行,并以指定的周期分隔。

语法

public void scheduleAtFixedRate(TimerTask task,
                                Date firstTime,
                                long period)

参数

task 指定要调度的任务。
firstTime 指定第一次时间执行任务的时间。
period 指定连续任务执行之间的时间间隔(以毫秒为单位)。

返回值

void类型。

异常

  • 抛出 IllegalArgumentException,如果 firstTime.getTime() < 0 或 period <= 0。
  • 抛出 IllegalStateException,如果任务已计划或取消,计时器已取消,或者计时器线程终止。
  • 如果任务或firstTime为空,则抛出NullPointerException

示例:

在下面的示例中,java.util.Timer.scheduleAtFixedRate() 方法用于安排给定任务从指定时间开始重复固定速率执行。

import java.util.*;

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

    //创建一个定时器任务
    TimerTask tt = new TimerTask() {
      public void run() {
        System.out.println("Working on the task.");
      };
    };
    
    //调度当前执行的任务
    //时间和当前日期,然后重复
    //1000毫秒的周期
    timer.scheduleAtFixedRate(tt, new Date(), 1000);
  }
}

上述代码的输出将是:

Working on the task.
Working on the task.
Working on the task.
Working on the task. 
and so on ...