Linux系列---【shell脚本-模拟手动跑每天的定时任务】-CSDN博客
阿里云国内75折 回扣 微信号:monov8 |
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6 |
问题背景
上线的时候经常会遇到这样的问题上线一个每天跑的定时任务一般跑最近一年的数据上线的时候需要手动跑过去最近一年的数据手动肯定不方便于是这里写了一个好用的shell脚本来降本增效。
shell脚本
#!/bin/bash
# 设置循环的日期范围
start_date="20230801"
end_date="20230810"
# 将日期转换为时间戳的函数
timestamp() {
date -d "$1" +%s
}
# 打印日志函数
log() {
echo "$(date "+%Y-%m-%d %H:%M:%S"): $1"
}
# 循环日期范围
current_date=$(date -d "$start_date" "+%Y%m%d")
end_timestamp=$(timestamp "$end_date")
while [ $(timestamp "$current_date") -le "$end_timestamp" ]; do
log "Processing date: $current_date"
# 执行 Curl 命令调用指定 URL
echo "curl -s -X GET http://localhost:8084/test?execDay=$current_date&success=true"
code=$(curl -s -X GET "http://localhost:8084/test?execDay=$current_date&success=true"|grep '"code":[0-9]*'|awk -F '[:,}]' '/"code":/{print $2}')
echo "response code: $code"
# 判断返回字段 code 是否为 200
if [ "$code" == 200 ]; then
log "Curl request successful. Continuing..."
# 可以在这里添加继续执行的逻辑
else
log "Curl request failed. Exiting..."
exit 1
fi
# 增加一天
current_date=$(date -d "$current_date + 1 day" "+%Y%m%d")
done