When writing a batch file to automate something on a Windows box, I've needed to pause its execution for several seconds (usually in a test/wait loop, waiting for a process to start). At the time, the best solution I could find uses ping (I kid you not) to achieve the desired effect. I've found a better write-up of it here, which describes a callable "wait.bat", implemented as follows:
@ping 127.0.0.1 -n 2 -w 1000 > nul
@ping 127.0.0.1 -n %1% -w 1000> nul
You can then include calls to wait.bat in your own batch file, passing in the number of seconds to sleep.
Apparently the Windows 2003 Resource Kit provides a Unix-like sleep command (at last!). In the meantime, for those of us still using Windows XP, Windows 2000 or (sadly) Windows NT, is there a better way?
I modified the sleep.py
script in the accepted answer, so that it defaults to one second if no arguments are passed on the command line:
import time, sys
time.sleep(float(sys.argv[1]) if len(sys.argv) > 1 else 1)
Using the
ping
method as outlined is how I do it when I can't (or don't want to) add more executables or install any other software.You should be pinging something that isn't there, and using the
-w
flag so that it fails after that amount of time, not pinging something that is there (like localhost)-n
times. This allows you to handle time less than a second, and I think it's slightly more accurate.e.g.
(test that 1.1.1.1 isn't taken)
Depending on your compatibility needs, either use
ping
:e.g. to wait 5 seconds, use
or on Windows 7 or later use
timeout
:The
timeout
command is available from Windows Vista onwards:Note: It does not work with input redirection - trivial example:
Even more lightweight than the Python solution is a Perl one-liner.
To sleep for seven seconds put this in the BAT script:
This solution only provides a resolution of one second.
If you need higher resolution then use the Time::HiRes module from CPAN. It provides
usleep()
which sleeps in microseconds andnanosleep()
which sleeps in nanoseconds (both functions takes only integer arguments). See the Stack Overflow question How do I sleep for a millisecond in Perl? for further details.I have used ActivePerl for many years. It is very easy to install.
You could use the Windows cscript WSH layer and this wait.js JavaScript file:
You can also use a .vbs file to do specific timeouts:
The code below creates the .vbs file. Put this near the top of you rbatch code:
The code below then opens the .vbs and specifies how long to wait for:
In the above code, the "1000" is the value of time delay to be sent to the .vbs file in milliseconds, for example, 1000 ms = 1 s. You can alter this part to be however long you want.
The code below deletes the .vbs file after you are done with it. Put this at the end of your batch file:
And here is the code all together so it's easy to copy: