Wednesday, September 26, 2007

Using WaitFor

In Vista, there is a command called waitfor, which as the name suggests, waits for a signal.  It is also the command to send the signal to awaiting waitfor instances.  Since waitfor comes with a timeout option, it's a good substitute for sleep (which, until I found out about waitfor, really was the number one thing I could not understand why it's missing from standard Windows command).

waitfor /T 10 SomeSignal

The above command will simply times out after 10 seconds.

OK, I lied.  There is actually a real substitute for sleep in Windows.  It's the timeout command.

timeout /T 10

That command does the exact same thing as the waitfor example, but you can cut short the sleep for waitfor with some signal, whereas for timeout you cut it short by pressing a key.

But obviously the purpose of the waitfor command is to allow you to start some long running command, do some other shorter things, and  wait for the long running command to finish before continuing.

REM Let's pretend we need to setup something

start cmd /c "DoSetup.exe & waitfor /S %COMPUTERNAME% /SI ThisSignal"

DoSomethingElse.exe

waitfor /T 60 ThisSignal

The first waitfor sends the signal, the second waits for the signal.  Of course you want to make sure DoSomethingElse.exe actually finishes before DoSetup.exe for this to work.  Otherwise the second waitfor will just timeout.  And I'd advise against waiting forever in the second waitfor, since if your DoSetup.exe fails or crashes and exits early, you'll most likely end up waiting too late for a signal that's already sent.

2 comments:

Unknown said...

'timeout' seems to be vista-only command. I generally use:

ping localhost -n 5 >NUL

For a 5 second delay. It works in 9x and NT

Arif Sukoco said...

Thanks lagshot, that's a good idea to use ping for time-specific delay.
Yes, 'timeout' is Vista and Win2K3 only.