用于在特定时间停止执行的批处理命令

时间:2014-07-11 09:48:17

标签: windows batch-file command-line cmd batch-processing

我使用批处理文件来触发测试方法执行,我在批处理文件中创建了一个循环,用于连续执行测试方法。我想在每天的特定时间停止这种连续执行(比如早上5点),请建议停止/退出批处理文件的命令。

请查看我的批处理文件详细信息,我的批处理文件无法退出@ 5AM,请指导我更正我的批处理文件状态

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

    timeout 900

    GOTO START

2 个答案:

答案 0 :(得分:3)

我不确定你的时间格式是什么,所以我包含了一个先前的子程序来进行24小时格式化。如果批处理文件正在运行且达到时间限制,此代码将停止处理。如果重新启动,它将一直运行,直到再次达到时间限制。

@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

答案 1 :(得分:0)

试试这个:

@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

代码将运行您的command to execute my test method并在循环中等待900秒,直到小时为5。此外,您应该在代码顶部放置一个@echo off,因为它会阻止批处理文件显示拉出路径。我还将您的command to execute my test method更改为rem command to execute my test method,因为cmd会忽略以rem开头的任何代码行,因此不会导致批处理文件崩溃。