user1787641
user1787641

Reputation: 331

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

Upvotes: 0

Views: 5737

Answers (2)

MC ND
MC ND

Reputation: 70923

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

Upvotes: 3

09stephenb
09stephenb

Reputation: 9806

Try this:

@echo off
rem -----------------------------
set hourtostopthecode=5
rem -----------------------------
:START
set timehour=%time:~0,2%
if %timehour% equ %hourtostopthecode% goto quitcode


rem command to execute my test method


timeout 900
GOTO START
:quitcode
echo Execution completed quit
timeout 1>nul
exit

The code will run your command to execute my test method and wait 900 seconds in a loop until the hour is 5. Also you should put a @echo off at the top of your code as it stop the batch file from displaying the pull path's. I have also changed your command to execute my test method to rem command to execute my test method because cmd will ignore any code line that starts with rem so it wont crash your batch file.

Upvotes: 0

Related Questions