并行启动多个任务并在Windows中等待它们?

时间:2018-03-01 13:21:01

标签: windows batch-file

如何在批处理脚本中并行执行某些任务并等待它们?

command1;

# command3, command4 and command5 should execute in sequence say task1
# command6, command7 and command8 should execute in sequence say task2
# both task1 and task2 should run independently

command3; command4; command5 | command6; command7; command8;

# should execute only after the above parallel tasks are completed

command9;

作为一个概念证明,我尝试了类似但不起作用的东西:

echo "Starting"
start /wait wait20.bat   
start /wait wait40.bat 
echo "Finishing"

wait20.bat看起来像:

echo "starting 20 seconds job"
timeout 20
echo "finishing 20 seconds job"

我做错了什么?

2 个答案:

答案 0 :(得分:4)

我认为this is是最简单的方法:

command1

(
   start "task1" cmd /C "command3 & command4 & command5"
   start "task2" cmd /C "command6 & command7 & command8"
) | pause

command9

评论this answer下面的详细信息。

答案 1 :(得分:1)

以下是如何使用任务列表和流程窗口标题完成的示例:

<强> launcher.cmd

@echo off
for /l %%a in (1,1,5) do start "worker%%a" cmd /c worker.cmd & timeout /t 1 >nul
:loop
timeout /t 2 >nul
tasklist /v /fi "imagename eq cmd.exe" /fo csv | findstr /i "worker" >nul && goto :loop
echo Workers finished

<强> worker.cmd

@echo off
set /a wait=2 + ( %RANDOM% %% 5 ) 
echo waiting for %wait%...
timeout /t %wait% >nul
echo I'm done!
timeout /t 2 >nul

我使用tasklist /v /fo csv获取标题。