Monday, May 9, 2016

Windows Batch Command to Wait for Specific Time

I wanted to start a command at a specific time without having to watch the clock and manually pressing enter. Here's one way to do it:

set STARTTIME=17:20:00.00
:UNTIL
timeout 5 > nul
if %time% lss %STARTTIME% goto UNTIL

The above code fragment waits until 5:20 PM before leaving the loop. It checks for the time every 5 second. If you need it to be more precise, you can change it to something smaller or not have "timeout" at all.

Windows command line has a number of special variables and %time% keeps the current time in the HH:MM:SS.cc format, where HH is the hour, MM minute, SS second, and cc centi-second (i.e. 100th of second).

You can turn this into a subroutine like the following and add it to the end of a batch file:

goto :eof
:WAITFOR
SETLOCAL
  SET _exptime=%1
:UNTIL
  timeout 5 > nul
  if %time% lss %_exptime% goto UNTIL
ENDLOCAL
goto :eof

then you can call this from other parts of the batch file:

CALL :WAITFOR 15:20:00.00

That's it.

No comments:

Post a Comment