定时启动其他脚本的shell,每批启动五个,时间间隔五分钟以上,支持时间戳和时间字符串

该脚本示例展示了如何用Shell定时启动多个脚本。它接受时间戳或时间字符串,计算延迟,按批处理执行脚本,并在每批之间设定随机或固定的时间间隔。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

以下是一个支持时间戳和时间字符串的定时启动其他脚本的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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值