Linux定時重啟
本文介紹如何設(shè)置定時重啟Linux主機(jī)
設(shè)置方法
說明
下面以Ubuntu的操作方式為例(CentOS的操作方式完全一樣)
在 Ubuntu 系統(tǒng)中,有兩種方法可以實現(xiàn)定時重啟,分別是使用 systemd 和 cron。
使用 systemd 設(shè)置定時重啟
1. 使用 root 用戶登錄終端。
2. 創(chuàng)建一個新的 systemd 服務(wù),例如 reboot.service。
sudo touch /etc/systemd/system/reboot.service
1. 使用文本編輯器(例如vi)打開該文件,并輸入以下內(nèi)容:
[Unit]
Description=Reboot Service
[Service]
Type=oneshot
ExecStart=/sbin/reboot
[Install]
WantedBy=multi-user.target
1. 保存并關(guān)閉文件。
2. 創(chuàng)建一個新的 systemd 定時器,例如 reboot.timer。
sudo touch /etc/systemd/system/reboot.timer
1. 使用文本編輯器打開該文件,并輸入以下內(nèi)容:
[Unit]
Description=Reboot Timer
[Timer]
OnCalendar=*-*-* 02:30:00
[Install]
WantedBy=timers.target
- 注意OnCalendar后面的時間格式是 - - 02:30:00,其中第一個表示星期,第二個表示月份,第三個表示日期,后面的時間格式是小時:分鐘:秒。
- 保存并關(guān)閉文件。
- 啟用并啟動定時器。
sudo systemctl enable --now reboot.timer
這樣就可以在每天早上 2:30 重啟了。
使用 cron 設(shè)置定時重啟
1. 使用 root 用戶登錄終端。
2. 打開 cron 配置文件:
crontab -e
1. 在文件末尾加入下面一行,表示每天凌晨 2:30 重啟:
30 2 * * * /sbin/reboot
- 注意這里的時間格式是分鐘 時 日 月 星期,依次對應(yīng)上面的 30 2 *
- 保存并退出。
這樣cron就會在每天早上2:30重啟系統(tǒng)了。
總結(jié)一下,使用systemd和cron都可以實現(xiàn)在 Ubuntu 系統(tǒng)中定時重啟的功能,兩種方法都需要使用root權(quán)限,并且重啟命令都是reboot。只是在時間格式上有所不同,具體可以參考上面的操作步驟。