java.util.Timer.schedule() 方法用于安排指定任务在指定时间执行。如果时间已经过去,则安排任务立即执行。
语法
public void schedule(TimerTask task,
Date time)
参数
task | 指定要安排的任务。 |
time | 指定时间任务执行时间。 |
返回值
void 类型。
异常
- 如果 time.getTime() 为负数,则抛出 IllegalArgumentException。
- 如果任务已计划或取消,则抛出 IllegalStateException 、计时器被取消,或计时器线程终止。
- 如果任务或时间为 null,则抛出 NullPointerException。
示例:
在下面的示例中,java.util.Timer.schedule() 方法用于安排给定任务在指定时间执行。
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 <= 5; i++) {
System.out.println("Working on the task.");
}
System.out.println("Task is finished.");
};
};
//调度要执行的任务
//当前时间和当前日期
timer.schedule(tt, new Date());
}
}
上述代码的输出将是:
Working on the task.
Working on the task.
Working on the task.
Working on the task.
Working on the task.
Working on the task.
Task is finished.