我有一个调用各种命令的批处理文件,其中一些命令偶尔会由于网络问题而失败。重试该命令通常会成功。
如何自动重试命令,直至达到设定的尝试次数?
这是一些旨在进一步解释的伪代码
call:try numTries "command and arguments"
exit
:try
REM execute %2, trying upto %1 times if it fails
%1 = %1 -1
eval %2
if %errorlevel%==0 exit \B
if %1 > 0 goto try
exit \B
Run Code Online (Sandbox Code Playgroud)
以下脚本就是您正在寻找的:
CALL :try numTries "command and arguments"
GOTO :EOF
:try
SET /A tries=%1
:loop
IF %tries% LEQ 0 GOTO return
SET /A tries-=1
EVAL %2 && (GOTO return) || (GOTO loop)
:return
EXIT /B
Run Code Online (Sandbox Code Playgroud)
try子程序的逻辑是这样的:
将尝试次数存储到变量中。
开始循环。检查tries变量。如果等于或小于 0,则返回。
评估命令和参数。
如果返回值为“成功”(ERRORLEVEL 为 0),则返回(从例程try),否则转到#2(循环的开头)。
没有 eval 和 > (几乎复制了 MatsT 答案的意大利面)
REM execute %2, trying upto %1 times if it fails
set count=%1
set command=%2
:DoWhile
if %count%==0 goto EndDoWhile
set /a count = %count% -1
call %command%
if %errorlevel%==0 goto EndDoWhile
if %count% gtr 0 goto DoWhile
:EndDoWhile
Run Code Online (Sandbox Code Playgroud)