for /l %%t in (1, 1, %1) do (
REM some commands that take a few minutes
CALL :shouldistop
if defined breakloop echo Loop broken when T=%%t&goto nextstep
)
:nextstep
REM some more commands that take a few minutes
....
GOTO :eof
:shouldistop
:: Assume time format is h:mm:ss.cc (24hr; suppressed-leading-zero for hours)
set "breakloop=%time::=%"
set /a breakloop=%breakloop:.=% / 10000
if %breakloop% gtr 605 goto :eof
set "breakloop="
goto :eof
Much depends on your time format. My time format is, eg 23:12:06.26 and that's the string that appears in the magic variable time
for me.
This code assumes that you use suppressed-leading-zero for the hour. Suppose we use 6:12:17.22
to trace how it works.
breakloop
is initialised to 6:12:17.22
with the colons removed = 61217.22
(see set /?
from the prompt for documentation, or there are thousands of examples on SO)
breakloop
then has its .
removed, yielding 6121722
and this is divided by 10000
, setting breakloop
to 612
Compare 612
to 605
- this is true, so goto end-of-file; otherwise, "set" the value of breakloop
to nothing which removes it from the environment (it becomes undefined).
Note that if you want to include seconds, then you'd use /100
and 60530
.
If you have leading-zeroes for the hour, then set breakloop
to 1%time::=%
initially, and use 10605
for the time (ie force-prefix the time with a 1
to ensure the calculation is performed in decimal, not octal)
=== without using subroutine
for /l %%t in (1, 1, %1) do (
REM some commands that take a few minutes
setlocal enabledelayedexpansion
set "now=!time!"
rem see whether hours is less than 10
if "!now:~1,1!==":" set "now=0!now!"
if "!now:~0,5!" gtr "06:05" endlocal& goto nextstep
endlocal
)
:nextstep
REM some more commands that take a few minutes
Use !now:~0,8!
to compare against 06:05:30
The issue here is that a string comparison needs to be invoked if the data contains anything other than numeric characters and therefore we need to leading-zero-pad any time before 10:00 since a string-comparison is done character-by-character so 11:20
is LESS than 6:05
as 1
is less than 6
.
The compare time must be in HH:MM format.
And we need to deal with extracting current time within a block, hence we need to invoke setlocal
to allow !var!
syntax and keep the endlocal
commands balanced with the setlocal
.
Much easier to use a subroutine, IMHO.