以下是一个支持时间戳和时间字符串的定时启动其他脚本的Shell脚本示例:
#!/bin/bash
# 定义要启动的脚本列表
scripts=(
"script1.sh"
"script2.sh"
"script3.sh"
"script4.sh"
"script5.sh"
"script6.sh"
"script7.sh"
"script8.sh"
"script9.sh"
"script10.sh"
)
# 定义时间戳或时间字符串
target_time="2022-01-01 00:00:00" # 时间字符串示例
# target_time=1640995200 # 时间戳示例
# 将时间字符串转换为时间戳
if [[ $target_time =~ ^[0-9]+$ ]]; then
target_timestamp=$target_time
else
target_timestamp=$(date -d "$target_time" +%s)
fi
# 计算任务执行时间
delay=$(($target_timestamp - $(date +%s)))
# 如果任务执行时间为负数,则表示该时间已过,不执行任务
if [[ $delay -lt 0 ]]; then
echo "Target time has passed."
exit 1
fi
# 计算批次数和每批启动的脚本数
batch_size=5
total_scripts=${#scripts[@]}
total_batches=$((($total_scripts + $batch_size - 1) / $batch_size))
# 循环启动脚本批次
for ((batch=0; batch<$total_batches; batch++)); do
start=$((batch * batch_size))
end=$((start + batch_size))
# 如果脚本已经全部启动完毕,则退出循环
if [[ $start -ge $total_scripts ]]; then
break
fi
# 启动一批脚本
for ((i=$start; i<$end && i<$total_scripts; i++)); do
./${scripts[$i]} &
done
# 等待一段时间再启动下一批脚本
sleep_time=$((5 * 60 + $RANDOM % 60)) # 随机等待5~6分钟
sleep $sleep_time
done
该脚本定义了一个要启动的脚本列表,并定义了一个时间戳或时间字符串作为目标执行时间。脚本将目标时间转换为时间戳,并计算任务执行时间。然后,脚本计算要启动的脚本批次数和每批启动的脚本数,并循环启动
#!/bin/bash
# 定义要执行的脚本列表
scripts=(
"/path/to/script1.sh"
"/path/to/script2.sh"
"/path/to/script3.sh"
"/path/to/script4.sh"
"/path/to/script5.sh"
"/path/to/script6.sh"
"/path/to/script7.sh"
"/path/to/script8.sh"
"/path/to/script9.sh"
"/path/to/script10.sh"
)
# 定义时间戳或时间字符串
target_time=$1
#target_time="2022-01-01 00:00:00" # 时间字符串示例
# target_time=1640995200 # 时间戳示例
# 将时间字符串转换为时间戳
if [[ $target_time =~ ^[0-9]+$ ]]; then
target_timestamp=$target_time
else
target_timestamp=$(date -d "$target_time" +%s)
fi
# 获取当前时间戳
now=$(date +%s)
# 计算任务执行时间
delay=$(($target_timestamp - $now))
# 如果任务执行时间为负数,则表示该时间已过,不执行任务
if [[ $delay -lt 0 ]]; then
echo "Target time has passed."
exit 1
fi
# 计算每批启动的脚本数量
batch_size=5
# 计算每批启动的时间间隔
batch_interval=300 # 5分钟
# 等待任务执行时间
sleep $delay
# 循环执行脚本
for (( i=0; i<${#scripts[@]}; i+=batch_size )); do
batch=${scripts[@]:i:batch_size}
for script in ${batch[@]}; do
$script &
done
sleep $batch_interval
done