在 Linux 系统中设置定时关机可以通过以下几种方法实现,根据你的需求选择最合适的方式:
shutdown
命令(一次性定时关机)sudo shutdown -h +30 # 30分钟后关机
-h
:表示关机(halt)。+30
:延迟时间(分钟),例如 +60
表示 1 小时后关机。bash
sudo shutdown -h 23:00 # 晚上11点关机
sudo shutdown -c # 取消已计划的关机
at
命令(单次任务)at
(如果未安装):
bash
sudo apt install at # Debian/Ubuntu
sudo yum install at # CentOS/RHEL
bash
echo "shutdown -h now" | at now + 2 hours
bash
echo "shutdown -h now" | at 23:00
bash
atq
bash
atrm <任务ID> # 通过 atq 获取ID
cron
任务(周期性定时关机)bash
crontab -e
添加一行(例如每天 23:00 关机):
0 23 * * * /sbin/shutdown -h now
分钟 小时 日 月 星期 命令
/sbin/shutdown
的完整路径(可通过 which shutdown
确认)。保存退出后,cron 会自动加载任务。
crontab -l # 查看任务
crontab -r # 删除所有任务(慎用)
systemd
定时器(适用于 systemd 系统)创建服务单元文件:
sudo nano /etc/systemd/system/shutdown.timer
内容如下(例如每天 23:00 关机):
[Unit]
Description=Daily Shutdown
[Timer]
OnCalendar=*-*-* 23:00:00
Persistent=true
[Install]
WantedBy=timers.target
关联服务文件:
sudo nano /etc/systemd/system/shutdown.service
内容:
[Unit]
Description=Shutdown
[Service]
Type=oneshot
ExecStart=/sbin/shutdown -h now
bash
sudo systemctl enable --now shutdown.timer
sudo
或 root 用户操作。nohup
或 disown
)。bash
journalctl -u shutdown.service # 针对 systemd
bash
grep "shutdown" /var/log/syslog
shutdown
或 at
。cron
或 systemd
。wall "Test message"
发送通知,避免误操作。