并行执行批处理文件并等到所有完成

时间:2013-12-24 05:11:09

标签: windows batch-file cmd

我有一个master batch文件,可以调用另一个列表batch文件。我想等到所有batch文件都被执行(不能说哪一个会执行得更快)并来到master batch文件来执行剩余的文件。

示例:

           a) master.bat            b) build.bat
              call build.bat           start web.bat        
              post.bat                 start db.bat                            

此处master.bat调用文件build.batbuild.bat文件并行运行web & db bat个文件,一旦执行,就必须返回master.bat并运行post.bat

任何人都可以指导我如何做到这一点。

5 个答案:

答案 0 :(得分:2)

终于得到了解决方案,但忘了更新:)

@echo off
setlocal
set "lock=%temp%\wait%random%.lock"

:: Launch processes asynchronously, with stream 9 redirected to a lock file.
:: The lock file will remain locked until the script ends.
start "" 9>"%lock%1" web.bat
start "" 9>"%lock%2" db.bat

:Wait for both processes to finish (wait until lock files are no longer locked)
1>nul 2>nul ping /n 2 ::1
for %%N in (1 2) do (
  (call ) 9>"%lock%%%N" || goto :Wait
) 2>nul

::delete the lock files
del "%lock%*"

:: Finish up
echo Done - ready to continue processing.

谢谢,

答案 1 :(得分:2)

如果您不介意使用 additional tool - Windows命令处理器不支持此功能,那么开箱即用"" - 你可以这样做没有需要"忙等待"或使用" lock"文件:

mparallel.exe --count=3 --shell first.bat : second.bat : third.bat
call post.bat

第一行将同时启动first.batsecond.batthird.bat 。它将返回,直到所有三个终止。我们在这里使用--shell来在shell中运行任务,这是BAT文件所必需的。三个BAT完成后,执行post.bat。可能是另一个 mparallel 电话。

答案 2 :(得分:0)

在master.bat中:

:flagfloop
set "flagfile=%temp%\%random%%random%%random%"
if exist "%flagfile%*" goto flagfloop
call build
:wbuild
if exist "%flagfile%*" timeout /t 10 >nul&goto wbuild
post.bat

在build.bat

for %%i in (web db) do (
 echo.>"%flagfile%%%i"
 start %%i.bat
)

在web.bat和db.bat中,就在批处理退出之前,      del“%flagfile %%% ~n0”> nul 2> nul

哪个应该选择一个随机的tempfile-prefix;在第三级.bat的持续时间内创建文件123321123web和123321123db,然后在两者完成时继续执行主程序(超时设置为10秒;您可以根据需要更改此选项)

答案 3 :(得分:0)

此问题与Wait For Commands to Finish

重复

您可以使用多个标记文件,每个运行的批处理文件一个。主批处理文件可以在输入时创建Flagfile.1,被调用的批处理文件可以在结束前删除它。

主批处理文件必须等待所有标记文件消失。例如,在主文件中:

echo X > flagfile.1
start build.bat 1 arg1
echo X > flagfile.2
start build.bat 2 arg2
.....
:wait
if exist flagfile.* goto wait
post.bat

在任何build.bat批处理文件中:

echo Do my process...
del flagfile.%1
exit /B

答案 4 :(得分:-1)

使用CALL command,如下所示:

master.bat

call build.bat              
call post.bat  
相关问题