CentOS 定时关机
在服务器的日常运维中,定时关机是一项非常重要的工作。当服务器长时间运行后,系统资源可能会出现瓶颈,对系统的稳定性产生影响。定时关机可以避免这种情况的发生,保障服务器的正常运行。
CentOS 定时关机的实现方法
CentOS 提供了多种方法来实现定时关机。以下是三种实现方法:
方法一:使用 crontab 命令
使用 crontab 命令添加一个定时任务,执行 shutdown 命令关机。例如,设置每天晚上23:00关机:
在终端中输入以下命令:
crontab -e
输入以下内容:
0 23 * * * /sbin/shutdown -h now
保存并退出。
方法二:使用 at 命令
使用 at 命令在指定时间执行 shutdown 命令关机。例如,设置在3小时后关机:
在终端中输入以下命令:
at now +3 hour
输入以下内容:
/sbin/shutdown -h now
保存并退出。
方法三:使用 systemd-timer
使用 systemd-timer 命令来实现定时关机,它是 Systemd 的一部分,可以替代传统的 cron 任务。
执行以下命令,创建一个定时器单元,设置在每天晚上23:00关机:
sudo systemctl edit --force --full shutdown.timer
输入以下内容:
[Unit]
Description=Shutdown at 23:00 every day
[Timer]
OnCalendar=*-*-* 23:00:00
[Install]
WantedBy=timers.target
保存并退出。
CentOS 定时关机的注意事项
在设置定时关机的过程中,需要注意以下事项:
确认关机时间,确保该时间没有关键任务在运行,同时也要保证该时间处于备份周期之外。
在执行定时关机前,确保保存了所有重要文件并将其备份。
在系统重启时,确保所有服务都已启动。
CentOS Timed Shutdown
Scheduled shutdown is an essential task in the day-to-day operation of a server. Long hours of system operations can lead to bottleneck of the system resources, which could significantly affect the system’s stability. Timed shutdowns prevent such problems from occurring and ensure the server’s smooth operation.
Methods of Implementing Timed Shutdown on CentOS
Multiple methods are available to implement timed shutdown on CentOS. Below are the three most commonly used methods:
Method One: Using the Crontab Command
Add a timed task using the crontab command to execute the shutdown command. For example, set the shutdown time to 11 pm every day:
Type the following command in the terminal:
crontab -e
Input the following content:
0 23 * * * /sbin/shutdown -h now
Save and exit.
Method Two: Using the At Command
Use the at command to execute the shutdown command at a specific time. For example, set to shut down in three hours:
Type the following command in the terminal:
at now +3 hour
Input the following content:
/sbin/shutdown -h now
Save and exit.
Method Three: Using Systemd-Timer
Use the systemd-timer command to implement timed shutdown, which is part of Systemd and can replace traditional cron tasks.
Type the following command to create a timing unit and set the shutdown time to 11 pm every day:
sudo systemctl edit --force --full shutdown.timer
Input the following content:
[Unit]
Description=Shutdown at 23:00 every day
[Timer]
OnCalendar=*-*-* 23:00:00
[Install]
WantedBy=timers.target
Save and exit.
Things to Consider When Implementing Timed Shutdown on CentOS
When configuring timed shutdown, consider the following:
Confirm the shutdown time and make sure that no critical tasks are running at that time, while also ensuring that the timing is outside the backup period.
Before executing timed shutdown, ensure that all critical files are saved and backed up.
After the system restarts, ensure that all services are running.

