2017-01-11 31 views
-3

我有大約24個批處理文件,我必須一次運行3個,並在完成第一個3之後,然後運行接下來的3個文件等等。如何並行運行三個批處理文件,並在完成第一次設置後運行另外三個批處理文件?

假設我有像1.bat,2.bat,3.bat等文件,我需要它們在完成前3個文件時運行前3個文件,然後我需要下3個文件運行,直到所有24個文件。

+2

SO上已經有了解決方案。你只需要爲他們的谷歌。 – jeb

+0

您可能感興趣的:[並行執行批處理文件並獲取每個退出代碼](http://stackoverflow.com/a/41051895)... – aschipfl

+0

IMO,問題應該已被關閉爲「太寬泛」或「必須包含MCVE」。 – halfer

回答

0
start 1.bat 
start 2.bat 
start /wait 3.bat 
start 4.bat 
start 5.bat 
start /wait 6.bat 

依此類推。這假設帶有/wait開關的批處理文件是最長的。如果這是不可能的,你可以使用這個腳本在這裏:

@echo off 

start bat1.bat 
start bat2.bat 
start bat3.bat 
call waitForFinish 
start bat4.bat 
start bat5.bat 
start bat6.bat 
call waitForFinish 
Goto:eof 

:waitForFinish 
set counter=0 
for /f %%i in ('tasklist /NH /FI "Imagename eq cmd.exe') do set /a counter=counter+1 
if counter GTR 2 Goto waitForFinish 

開始3批文件後調用「功能」 waitForFinish。這將檢查它是否找到多於1個正在運行的命令行進程(其中一個用於運行的批處理文件,因此它將始終存在,另外一行位於輸出之上)並對其找到的每個窗口計數。
如果該計數器大於2,它將一次又一次地執行相同的操作,直到只有正在運行的批處理文件窗口是找到的唯一cmd.exe進程。如果是這種情況,腳本將返回到腳本的頂部以啓動接下來的三個腳本。

+0

我試着運行你給出的相同的代碼。結果是: 前三個批處理文件運行並關閉,但計數器值仍大於1,且循環連續重複。接下來的三個批處理文件沒有運行。請建議我, –

+0

而不是使用'findstr'來過濾,你應該使用'tasklist'的過濾功能(參見它的'/ FI'選項)... – aschipfl

+0

@UmamaheswaraReddyAmbati看起來還有一條額外的線路導致問題... aschipfl的建議後,我改變了一下命令,並將錯誤的0更改爲2. – geisterfurz007

0

以下腳本並行執行三個批處理文件並等待它們完成?基本上,它允許每個批處理文件將其輸出重定向到一個臨時文件,只要批處理文件仍在運行,該文件就會被寫入鎖定。一旦批處理文件終止,臨時文件就可以被寫入,因此它可以並且將被刪除。因此,這裏是代碼:

@echo off 

rem /* Execute three batch files in parallel, redirect their STDERR output 
rem into individual temporary files: */ 
start "" cmd /C 2^> "1.tmp" "1.bat" 
start "" cmd /C 2^> "2.tmp" "2.bat" 
start "" cmd /C 2^> "3.tmp" "3.bat" 

rem // Call sub-routine containing a polling loop: 
call :POLL "1.tmp" "2.tmp" "3.tmp" 

exit /B 


:POLL {val_temp_file}* 
rem /* Establish polling loop that tries to delete the temporary files; 
rem if a batch file is still running, the respective temporary file 
rem is not yet accessible, so deletion fails: */ 
:LOOP 
rem // Delay execution to give processor some time: 
> nul timeout /T 1 /NOBREAK 
rem /* `for /F` loop to capture the STDERR output of the `del` command; 
rem remember that `del` does not set the `ErrorLevel` unfortunately: */ 
for /F "delims=" %%E in (' 
    rem/ Discard STDOUT output and redirect STDERR output adequately: ^&^
    2^>^&1 ^> nul ^(^ 
     rem/ `if exist` even works for already opened/accessed files: ^&^
     for %%F in ^(%*^) do if exist "%%~F" del "%%~F"^ 
    ^) 
') do (
    rem // Loop iterates, so there is STDERR output, hence loop back: 
    goto :LOOP 
) 

exit /B 
1

該解決方案使用在this answer介紹的方法:

@echo off 
setlocal EnableDelayedExpansion 

for /L %%i in (1,3,22) do (
    set /A N1=%%i, N2=%%i+1, N3=%%i+2 
    (start "" !N1!.bat & start "" !N2!.bat & start "" !N3!.bat) | set /P "=" 
) 

在這種方法的第一個線程進入一個等待狀態不消耗CPU,直到三個開始的批處理文件結束。寫起來也很容易(而且看起來不錯!);

+0

我知道有一種方法使用管道,但我記不住......: -/+1! – aschipfl

相關問題