Disclaimer: this is not the “ideal” solution, so don’t bother beating me over the head with that like done to those recommending ping

When possible, use timeout for sure. But as noted in the comments, that’s not always an option (e.g. in non-interactive mode). After that, I agree that the ping “kludge” is perhaps the next best option, as it is very simple. That said, I offer another option… embed some VB Script.

The basis of this solution has all sorts of application beyond this. Often VBS can do things that batch cannot, or at the very least do so with drastically more ease. Using the technique illustrated here, you can mix the two (not “seamlessly”, but “functionally”…).

Here’s a one liner, to create a temp script, execute it, then delete it. The script does the sleeping for you (for 3 seconds in this example).

echo WScript.Sleep 3000 > %temp%sleep.vbs & cscript %temp%sleep.vbs %sleepMs% //B & del %temp%sleep.vbs

Here’s basically the same thing, written a bit differently:

set sleepMs=3000 & set sleepVbs=%temp%sleep.vbs & echo WScript.Sleep WScript.Arguments(0) > %sleepVbs% & cscript %sleepVbs% %sleepMs% //B & del %sleepVbs%

And then finally, like ping, CScript itself has a timeout option! So, if you enter an infinite loop in the script, you can let the interpreter enforce the duration. Note, this is a “busy” operation, which eats the CPU, and therefore I don’t recommend it when you can use the WScript.Sleep procedure, but I present it as a conceptual option for the sake of completeness:

set sleepSec=3 & set sleepVbs=%temp%sleep.vbs & echo While True > %sleepVbs% & echo Wend >> %sleepVbs% & cscript %sleepVbs% //B //T:%sleepSec% & del %sleepVbs%

Leave a Reply

Your email address will not be published. Required fields are marked *