Search code examples
windowsbatch-filecommand-linecmdbatch-processing

Batch command for stopping execution at specific time


I am using batch file to trigger test methods execution, I have created a loop in batch file for continuous execution of test methods. I want to stop this continuous execution at specific time everyday (like 5AM in the morning), Please do suggest the command to stop/quit the batch file execution.

Please view my batch file details below, my batch file fails to quit @5AM, Please guide to correct my batch file condition

:START
    ECHO set timehour=%time:~0,2%
if %timehour% gtr 5 (echo Execution completed quit)
    
    @REM command to execute my test methods
    
    timeout 900
    
    GOTO START

Solution

  • i'm not sure what your time format is, so i included a previous subroutine to do 24h formatting. This code will stop the processing if the batch file was running and the time limit is reached. If it is restarted, it will run until the time limit is reached again.

    @echo off
    
        setlocal enableextensions 
        set "oldRun="
        set "timeLimit=05:00:00,00"
        
    :start
        
        :: Test if the time limit has been reached 
        :: Only stop the process if 
        ::    - it was still running 
        ::    - and the time limit is reached
    
        call :getTime24h now
        if defined oldRun if "%oldRun%" leq "%timeLimit%" if "%now%" geq "%timeLimit%" (
            echo TIME LIMIT REACHED
            goto :endTests
        ) 
        set "oldRun=%now%"
    
    :runTests
        :: whatever goes here
        echo running at %now%
        
        :: here we go again
        goto :start
    
    :endTests    
        :: Cleanup what needs to be cleaned and exit
        :: ...
        
        endlocal
        exit /b
    
    :: Subroutine to get a 24h format time    
    
    :getTime24h returnVariable
        setlocal enableextensions
        set "ts=%time%"
        if "%ts:pm=%"=="%ts%" ( set "adjust=0" ) else ( set "adjust=12" )
        for /f "tokens=1-4 delims=:-.,apm " %%a in ("%ts%") do ( set /a "h=100%%a+adjust", "m=100%%b", "s=100%%c", "c=100%%d" )
        endlocal & set "%~1=%h:~-2%:%m:~-2%:%s:~-2%,%c:~-2%" & exit /b