Linux-Skills:定时自动执行脚本或者其他命令,例如实现定时自动开关机
Intro
在管理服务器的时候,有时候需要服务器自动开关机,或者定期执行某些指令。linux自带的crontab命令可以实现定时自动执行的命令,在终端内 $ sudo crontab -e
后编辑文件中的内容即可。
测试机器:ubuntu 22.04;
Solution
1. 终端内执行 $ sudo crontab -e
:
执行 $ sudo crontab -e
:
$ sudo crontab -e
第一次执行的话会弹出让你选择编辑器的选项,我选择vim。
2. 按照规定格式添加命令:
如果我想实现每周三22:00执行一个脚本,可以在 “1.” 打开的文件中添加如下命令:
0 15 * * 3 /path/to/your/script.sh
这里各部分的含义如下:
- 0: 分钟,表示0分钟。
- 22: 小时,即晚上22点。
- *: 代表每月的每一天。
- *: 代表每年的每一月。
- 3: 代表星期中的第三天,即周三(在cron中,周日是一周的第一天,即0,周一到周六分别是1到6)。
- /path/to/your/script.sh 是您的脚本文件的完整路径,需要替换为实际路径。
注意,各变量之间有空格。
比如我想在每周天22点服务器自动关机,早上8点自动开机,可以撰写一个脚本。
以下是我写的脚本,叫 shutdown_wake.sh
,其接受一个参数,代表关机后多少小时后重启:
#!/bin/bash
# Function to display script usage
function display_help {
echo "Usage: $0 [-h|--help] <shutdown_hours>"
echo " -h, --help Display this help message."
echo " <shutdown_hours> Number of hours until shutdown and wakeup."
exit 0
}
# Check if the help option is provided
if [ "$1" == "-h" ] || [ "$1" == "--help" ]; then
display_help
fi
# Check if the required argument is provided
if [ $# -eq 0 ]; then
echo "Please provide the number of hours for shutdown as an argument."
display_help
exit 1
fi
# Validate if the argument is a valid number
if ! [[ "$1" =~ ^[0-9]+(\.[0-9]+)?$ ]]; then
echo "Invalid input. Please provide a valid number for shutdown hours."
exit 1
fi
shutdown_hours=$1
# Round the result to the nearest integer
shutdown_seconds=$(echo "($shutdown_hours * 3600 + 0.5)/1" | bc)
echo "The system will shut down and wake up after $shutdown_hours hours."
# Use rtcwake to shut down and wake up the system
sudo rtcwake -m off -s $shutdown_seconds
#rtcwake -m off -s $shutdown_seconds
# Add any commands to be executed after the system restarts
echo "The system has awakened."
将该脚本保存在某一路径下,重复"1. "
中的 $ sudo crontab -e
打开编辑文件,增加如下内容:
0 22 * * * /path/to/shutdown_wake.sh 10
参数10代表关机10小时后重启。