How to sleep in a batch file?
Here's a haxxorish way to pause for a second in a batch file:
PING 400.500.600.700 > NUL
I've googled but I'm not sure there are any better ones.. any ideas? :)
Server Fault is a question and answer site for system and network administrators. It only takes a minute to sign up.Sign up to join this community
The correct way to do this is to use the
timeout command, introduced in Windows 2000.
To wait 30 seconds:
timeout /t 30
The timeout would get interrupted if the user hits any key; however, the command also accepts the optional switch
/nobreak, which effectively ignores anything the user may press, except an explicit
timeout /t 30 /nobreak
Additionally, if you don't want the command to print its countdown on the screen, you can redirect its output to
timeout /t 30 /nobreak > NUL
The ping one (above) is a good one- but only works if connected to a network.
A bit of script that will delay is below:
set /a secondsend=%TIME:~6,2%+10
if %secondsend% GTR 59 set /a secondsend=secondsend-60
if %TIME:~6,2% NEQ %secondsend% goto waithere
This will pause from between 9-10 seconds (the first second isn't accurate due to using the TIME command- and it could be halfway through a second before you begin).
If works by setting 'secondsend' to the current second of the pc clock, then adding 10 to it (the delay). If it's greater than 59 taking 60 off as it's wrapped around to next minute. Then there is a loop which checks the current second with 'secondsend'- once they match the script continues.
If you want to delay by a different period 2-59 then alter the 10 in the second line (I say 2-59 as the first second might not be a full second, so 2 could be say, 1.2 seconds for example).
Sorry it's so longwinded but thought I'd explain how the routine works.