温馨提示×

ubuntu定时器怎样定时重启

小樊
57
2026-10-18 17:46:18
栏目: 智能运维

在 Ubuntu 中,定时重启通常通过 cron 或 systemd timer 来实现。下面给你几种常见、可靠的方法。


一、使用 cron 定时重启(最常用)

1. 编辑 root 的 crontab

定时重启必须用 root 权限:

sudo crontab -e

2. 添加重启任务

例如:

每天凌晨 3 点重启

0 3 * * * /sbin/reboot

每周日凌晨 4 点重启

0 4 * * 0 /sbin/reboot

每 7 天重启一次(例如每月 1 号和 15 号)

0 3 1,15 * * /sbin/reboot

3. 保存并退出

cron 会自动生效,无需重启服务。

✅ 查看已有任务:

sudo crontab -l

二、使用 shutdown 命令(更优雅)

有时推荐用 shutdown 而不是 reboot,可以让系统正常关闭服务:

0 3 * * * /sbin/shutdown -r now

-r 表示重启,now 表示立即执行。


三、使用 systemd timer(更现代,推荐服务器)

1. 创建 service

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

内容:

[Unit]
Description=Scheduled Reboot

[Service]
Type=oneshot
ExecStart=/sbin/reboot

2. 创建 timer

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

示例(每天 3:00):

[Unit]
Description=Daily Reboot Timer

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

[Install]
WantedBy=timers.target

3. 启用并启动

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

✅ 查看状态:

systemctl list-timers

四、只重启一次(临时任务)

sudo shutdown -r 03:00

或 30 分钟后:

sudo shutdown -r +30

五、注意事项(很重要)

  1. 确保 cron 正在运行

    sudo systemctl status cron
    
  2. 不要频繁重启,避免影响服务

  3. 重要数据请先保存

  4. 如果是云服务器,确认控制台不会阻止重启


如果你愿意,可以告诉我:

  • Ubuntu 版本(18.04 / 20.04 / 22.04 / 24.04)
  • 是物理机 / 虚拟机 / 云服务器
  • 想每天 / 每周 / 指定时间

我可以帮你写一份完全合适的配置。

0 踩