如果批处理命令在给定时间段内未终止,请停止该命令



我有一个简单的批处理文件,它一个接一个地运行一堆PHP文件。有时,其中一些 php 文件挂起,发生这种情况时,整个批处理文件将停止执行在此之后的文件。

有没有办法停止运行命令,并在给定时间段后在批处理脚本中继续执行下一个命令?

到目前为止,我的批处理文件仅包含大约 800 行,命令类似于以下内容:

php72 ../simulation.php --version 0.9.0.4 --hashsimmilar false --thinkahead 0 --detailed 0 --outfile catacombs.outfile.csv --workingdir "C:/xampp/htdocs/rpg_prog/" --customfight 1,2,,,,1,,,1,,0,0,0,Catacombs1
php72 ../simulation.php --version 0.9.0.4 --hashsimmilar false --thinkahead 1 --detailed 0 --outfile catacombs.outfile.csv --workingdir "C:/xampp/htdocs/rpg_prog/" --customfight 1,2,,,,1,,,1,,0,0,0,Catacombs1
php72 ../simulation.php --version 0.9.0.4 --hashsimmilar false --thinkahead 2 --detailed 0 --outfile catacombs.outfile.csv --workingdir "C:/xampp/htdocs/rpg_prog/" --customfight 1,2,,,,1,,,1,,0,0,0,Catacombs1

例如,如果上述列表中的第二行挂起,则整个批处理文件将挂起,第三行将永远不会执行。

鉴于没有任何其他php72.exe进程,您可以在每个php72调用前面加上start "" /B,并在每个php72调用后放置以下行(如果您不想强制终止任务,请删除 /F 选项(:

timeout /T 10 /NOBREAK > nul
taskkill /IM "php72.exe" /F > nul 2>&1

>后缀只是避免抛出任何(错误(消息。


为了不必多次复制上述行,您还可以将以下代码放在批处理文件的顶部:

@echo off
rem // Read all lines from this batch file that begin with `php72 ` and iterate over them:
for /F "delims=" %%C in ('
    findstr /BIC:"php72 " "%~f0"
') do (
    rem // Execute the currently iterated `php72` command line:
    start "" /B %%C
    rem // Wait for some time:
    timeout /T 10 /NOBREAK > nul
    rem // Kill the `php72` process (or actually all of them) if still running:
    taskkill /IM "php72.exe" /F > nul 2>&1
)
rem // Avoid to fall into the `php72` command lines another time:
exit /B
rem // These are your lines:
php72 ../simulation.php --version 0.9.0.4 --hashsimmilar false --thinkahead 0 --detailed 0 --outfile catacombs.outfile.csv --workingdir "C:/xampp/htdocs/rpg_prog/" --customfight 1,2,,,,1,,,1,,0,0,0,Catacombs1
php72 ../simulation.php --version 0.9.0.4 --hashsimmilar false --thinkahead 1 --detailed 0 --outfile catacombs.outfile.csv --workingdir "C:/xampp/htdocs/rpg_prog/" --customfight 1,2,,,,1,,,1,,0,0,0,Catacombs1
php72 ../simulation.php --version 0.9.0.4 --hashsimmilar false --thinkahead 2 --detailed 0 --outfile catacombs.outfile.csv --workingdir "C:/xampp/htdocs/rpg_prog/" --customfight 1,2,,,,1,,,1,,0,0,0,Catacombs1

当然,您可以将php72命令行放在单独的文件中,然后需要相应地调整for /F循环:

rem // Specify appropriate text file:
for /F "usebackq delims=" %%C in ("D:pathtofile.txt") do (
    rem // Same loop body as above...
)