对接口模拟请求shell脚本

#!/bin/bash

# API地址配置(Get)
API_URL="https://ssss"

# 每日随机请求次数(38-60次)
REQUEST_COUNT=$(( RANDOM % 23 + 38))  # 生成38到60的随机数

# 生成时间窗口函数
calculate_window() {
    local current_ts=$(date +%s)
    local today_start=$(date -d "today 09:00:00" +%s)
    local today_end=$(date -d "today 21:00:00" +%s)

    if [ $current_ts -gt $today_end ]; then
        start=$(date -d "tomorrow 09:00:00" +%s)
        end=$(date -d "tomorrow 21:00:00" +%s)
    else
        start=$today_start
        end=$today_end
    fi

    effective_start=$(( current_ts > start ? current_ts : start ))
}

# 生成随机时间点
generate_times() {
    calculate_window
    local window_duration=$(( end - effective_start ))

    if [ $window_duration -le 0 ]; then
        echo "错误:当前不在有效时间窗口(09:00-21:00)"
        exit 1
    fi

    # 生成并排序时间戳
    timestamps=()
    for ((i=0; i<REQUEST_COUNT; i++)); do
        random_offset=$(( RANDOM % window_duration ))
        timestamps+=( $(( effective_start + random_offset )) )
    done
    timestamps=( $(printf "%s\n" "${timestamps[@]}" | sort -n) )
}

# 执行请求
execute_requests() {
    echo "今日计划执行 ${REQUEST_COUNT} 次,时间分布如下:"
    printf "%s\n" "${timestamps[@]}" | xargs -I{} date -d @{} "+%H:%M:%S"

    for ts in "${timestamps[@]}"; do
        local current_ts=$(date +%s)
        local remaining=$(( ts - current_ts ))

        if [ $remaining -gt 0 ]; then
            echo "下一次执行:$(date -d "@$ts" '+%H:%M:%S'),等待 ${remaining} 秒..."
            sleep $remaining
        fi

        # 发送请求并显示结果
        if curl -s -o /dev/null -w "状态码: %{http_code} 时间: %{time_total}s" "$API_URL"; then
            echo " - 请求成功 @ $(date '+%H:%M:%S')"
        else
            echo " - 请求失败 @ $(date '+%H:%M:%S')"
        fi
    done
}

# 主程序
generate_times
execute_requests

echo "今日随机 ${REQUEST_COUNT} 次请求全部完成"

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值