用shell控制在某个指定时刻执行命令

这种时间变动比较大,用cron不适合,且cron精度也不够

run_at.sh

#!/bin/bash

# 检查是否输入了时间戳参数
if [ "$#" -ne 1 ]; then
  echo "Usage: $0 yyyymmddhhmmss"
  exit 1
fi

timestamp=$1

# 解析目标时间并获取其Unix时间戳(秒)和纳秒部分
target_seconds=$(date -d "${timestamp:0:8} ${timestamp:8:2}:${timestamp:10:2}:${timestamp:12:2}" +%s)
target_nanoseconds=0

# 获取当前时间的Unix时间戳(秒)和纳秒部分
current_seconds=$(date +%s)
current_nanoseconds=$(date +%N)

# 计算需要等待的总纳秒数
wait_seconds=$((target_seconds - current_seconds))
wait_nanoseconds=$((target_nanoseconds - current_nanoseconds))

# 如果纳秒差为负,则借位
if [ "$wait_nanoseconds" -lt 0 ]; then
  wait_seconds=$((wait_seconds - 1))
  wait_nanoseconds=$((wait_nanoseconds + 1000000000))
fi

# 汇总等待时间的秒部分和纳秒部分
wait_time=$(echo "$wait_seconds + $wait_nanoseconds / 1000000000" | bc -l)

# 检查如果需要等待的时间为负数,说明输入的时间戳已过
if (( $(echo "$wait_time < 0" | bc -l) )); then
  echo "The input timestamp has already passed."
  exit 1
fi

# 等待指定时间
sleep "$wait_time"

# 显示当前时间,精确到毫秒
date +'%Y-%m-%d %H:%M:%S:%3N'

 

Leave a Reply

Your email address will not be published. Required fields are marked *