Waiting for parallel batch scripts

前端 未结 4 1694
盖世英雄少女心
盖世英雄少女心 2020-11-28 12:09

I have 4 batch files. I want to run one.bat and two.bat at once, concurrently. After completion of these two batch files, three.bat an

相关标签:
4条回答
  • 2020-11-28 12:49

    Create a master.bat file that starts one.bat and two.bat. When one.bat and two.bat end correctly, they echo to file they have finished

    if errorlevel 0 echo ok>c:\temp\OKONE
    if errorlevel 0 echo ok>c:\temp\OKTWO
    

    Then the master.bat wait for the existence of the two files

    del c:\temp\OKONE
    del c:\temp\OKTWO
    start one.bat
    start two.bat
    :waitloop
    if not exist c:\temp\OKONE (
        sleep 5
        goto waitloop
        )
    if not exist c:\temp\OKTWO (
        sleep 5
        goto waitloop
        )
    start three.bat
    start four.bat
    

    Another way is to try with the /WAIT flag

    start /WAIT one.bat
    start /WAIT two.bat
    

    but you don't have any control on errors.

    Here's some references

    http://malektips.com/xp_dos_0002.html

    http://ss64.com/nt/sleep.html

    http://ss64.com/nt/start.html

    0 讨论(0)
  • 2020-11-28 12:53

    I had this same dilemma. Here's the way I solved this issue. I used the Tasklist command to monitor whether the process is still running or not:

    :Loop
    tasklist /fi "IMAGENAME eq <AAA>" /fi "Windowtitle eq <BBB>"|findstr /i /C:"<CCC>" >nul && (
    timeout /t 3
    GOTO :Loop
    )
    echo one.bat has stopped
    pause
    

    You'll need to tweak the

    <AAA>, <BBB>, <CCC>

    values in the script so that it's correctly filtering for your process.

    Hope that helps.

    0 讨论(0)
  • 2020-11-28 12:58

    This is easily done using a much simplified version of a solution I provided for Parallel execution of shell processes. Refer to that solution for an explanation of how the file locking works.

    @echo off
    setlocal
    set "lock=%temp%\wait%random%.lock"
    
    :: Launch one and two asynchronously, with stream 9 redirected to a lock file.
    :: The lock file will remain locked until the script ends.
    start "" cmd /c 9>"%lock%1" one.bat
    start "" cmd /c 9>"%lock%2" two.bat
    
    :Wait for both scripts to finish (wait until lock files are no longer locked)
    1>nul 2>nul ping /n 2 ::1
    for %%N in (1 2) do (
      ( rem
      ) 9>"%lock%%%N" || goto :Wait
    ) 2>nul
    
    ::delete the lock files
    del "%lock%*"
    
    :: Launch three and four asynchronously
    start "" cmd /c three.bat
    start "" cmd /c four.bat
    
    0 讨论(0)
  • 2020-11-28 12:58

    Just adding another way, maybe the shortest.

    (one.cmd | two.cmd) && (three.cmd | four.cmd)
    

    Concept is really straight forward. Start one and 2 in paralel, once done and errorlevel is 0 run three and four.

    0 讨论(0)
提交回复
热议问题