温馨提示×

ubuntu定时器如何定时重启

小樊
49
2026-10-09 23:25:43
栏目: 智能运维

在 Ubuntu 中,最常用、最可靠的“定时重启”方式是使用 systemd 定时器(systemd timer) 或传统的 cron。下面分别说明。


方法一:使用 cron(最简单)

1. 编辑 root 的 cron

sudo crontab -e

2. 添加定时重启任务

例如:每天凌晨 3 点重启

0 3 * * * /sbin/reboot

常用示例

  • 每周日 4:00 重启
0 4 * * 0 /sbin/reboot
  • 每 6 小时重启
0 */6 * * * /sbin/reboot

⚠️ cron 使用的是系统本地时间
⚠️ 必须写 /sbin/reboot 或使用 systemctl reboot


方法二:使用 systemd Timer(推荐,更现代)

1. 创建 service

sudo nano /etc/systemd/system/reboot-task.service

内容:

[Unit]
Description=Reboot System

[Service]
Type=oneshot
ExecStart=/usr/bin/systemctl reboot

2. 创建 timer

sudo nano /etc/systemd/system/reboot-task.timer

每天 03:00 重启示例:

[Unit]
Description=Daily Reboot Timer

[Timer]
OnCalendar=*-*-* 03:00:00
Persistent=true

[Install]
WantedBy=timers.target

3. 启用并启动

sudo systemctl daemon-reexec
sudo systemctl enable --now reboot-task.timer

4. 查看状态

systemctl list-timers

方法三:一次性定时重启(临时)

sudo shutdown -r 03:00

或

sudo at now + 6 hours
> reboot
> Ctrl+D

注意事项

  • 服务器重启会中断服务
  • 确保有自动恢复机制(如 docker / systemd 自启)
  • 不建议频繁重启生产环境

如果你说明:

  • 是 服务器 / 桌面
  • 想 每天 / 每周 / 每隔几小时
  • 是否使用 Docker

我可以帮你直接写完整配置。

0 踩