在 Java 中計劃任務執行
Timer 類中的方法之一是 void schedule(Timertask task, Date time) 方法。此方法計劃在指定時間執行指定的任務。如果時間已過去,則它會計劃立即執行任務。
宣告 −java.util.Timer.schedule(Timertask task, Date time) 的宣告如下所示 −
public void schedule(Timertask task, Date time)
schedule(Timertask task, Date time) 方法丟擲了一些異常。它們如下所示 −
| IllegalArgumentException | 如果 time.getTime() 為負數,則會丟擲此異常。 |
| IllegalStateException | 如果任務事先已計劃或取消,計時器已取消或計時器執行緒已終止,則會丟擲此異常。 |
| NullPointerException | 如果任務或時間為空,則會丟擲此異常。 |
示例
import java.util.*;
class MyTask extends TimerTask {
public void run() {
System.out.println("Task is running");
}
}
public class Example {
public static void main(String[] args) {
Timer timer = new Timer(); // creating timer
TimerTask task = new MyTask(); // creating timer task
timer.schedule(task, new Date()); // scheduling the task
}
public void run() {
System.out.println("Performing the given task");
}
}輸出
Task is running
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP