我有一个每小时运行的 cron 作业。它访问一个 xml 提要。如果 xml 提要不可用(这似乎每天发生一次),它会创建一个“失败”文件。这个“失败”文件中包含一些元数据,并在下一小时脚本再次运行并且 XML 提要再次工作时被删除。
我想要的是在第一个任务后几分钟运行第二个 cron 作业,查看目录中的“失败”文件,如果存在,重试第一个 cron 作业。
我知道如何设置 cron 作业,只是不知道如何使脚本像那样有条件。我是否以完全错误的方式解决这个问题?
可能。也许您最好让原始脚本休眠并重试(有限)次。
Sleep 是一个 shell 命令,shell 支持循环,所以它看起来像这样:
for ((retry=0;retry<12;retry++)); do
try the thing
if [[ -e my_xlm_file ]]; then break; fi
sleep 300
# five minutes later...
done
作为要运行的命令,请尝试:
/bin/bash -c 'test -e failurefile && retrycommand -someflag -etc'
如果失败文件存在,它将运行重试命令
为什么不让您的脚本在成功完成后触摸状态文件。让它每 5 分钟运行一次,并让脚本的第一次检查是查看状态文件是否小于 60 分钟,如果它是年轻的,则退出,如果它是旧的,则获取。
我同意 MarkusQ 的观点,即您应该重试原始作业,而不是创建另一个作业来观看第一个作业。
看看这个工具,使重试更容易:https ://github.com/kadwanev/retry
您可以非常轻松地将原始 cron 包装在重试中,并且失败文件的最终存在将指示它是否在重试之后失败。
如果有人需要bash
脚本来 ping 端点(例如,通过 运行计划的 API 任务cron
),重试它,如果响应状态不好,则:
#!/bin/bash
echo "Start pinch.sh script.";
# run 5 times
for ((i=1;i<=5;i++))
do
# run curl to do a POST request to https://www.google.com
# silently flush all its output
# get the response status code as a bash variable
http_response=$(curl -o /dev/null -s -w "%{response_code}" https://www.google.com);
# check for the expected code
if [ $http_response != "200" ]
then
# process fail
echo "The pinch is Failed. Sleeping for 5 minutes."
# wait for 300 seconds, then start another iteration
sleep 300
else
# exit from the cycle
echo "The pinch is OK. Finishing."
break;
fi
done
exit 0