利用 Runtime.getRuntime().exec() 執行 Windows 原生 shutdown 命令,參數 -s 關機,-t 設定倒數秒數。
import java.util.Scanner;
import java.io.IOException;
public class ShutdownTimer {
public static void shutdown() {
System.out.print("請輸入多少分鐘後關機: ");
Scanner scanner = new Scanner(System.in);
int minutes = scanner.nextInt();
int seconds = minutes * 60;
Runtime runtime = Runtime.getRuntime();
String cmd = "shutdown -s -t " + seconds;
try {
runtime.exec(cmd);
System.out.println("已設定 " + minutes + " 分鐘後自動關機。");
} catch (IOException e) {
System.err.println("執行關機命令失敗: " + e.getMessage());
e.printStackTrace();
}
}
public static void main(String[] args) {
shutdown();
}
}
| 參數 | 作用 |
|---|---|
| -s | 關機 |
| -r | 重啟 |
| -t xxx | 設定倒數秒數 |
| -a | 取消已排程的關機/重啟 |
| -f | 強制關閉應用程式 |
shutdown 可能被系統攔截。shutdown -h +min 或 systemctl poweroff。ProcessBuilder 替代 Runtime.exec(),支援更豐富的進程控制。