How to sleep in batch script

| | 0 Comments

Info

A question that could come to our mind when you write a batch script is: how can I sleep/wait for few seconds?

First possible solution

Googling, I found that most of the times the main suggestion is to use ping like:

ping -n XXX 127.0.0.1 >nul

There would be some unexpected result using the ping command, specially if you don’t have any network card or all of them are disconnected.

Second possible solution

The best solution would be to use the built-in timeout command which works only for OS > Windows Vista.

TIMEOUT [/T] timeout [/NOBREAK]

Description:
    This utility accepts a timeout parameter to wait for the specified
    time period (in seconds) or until any key is pressed. It also
    accepts a parameter to ignore the key press.

Parameter List:
    /T        timeout       Specifies the number of seconds to wait.
                            Valid range is -1 to 99999 seconds.

    /NOBREAK                Ignore key presses and wait specified time.

    /?                      Displays this help message.

NOTE: A timeout value of -1 means to wait indefinitely for a key press.

Examples:
    TIMEOUT /?
    TIMEOUT /T 10
    TIMEOUT /T 300 /NOBREAK
    TIMEOUT /T -1

Third possible solution

Somebody could also add: why I cannot use the sleep.exe command that’s in the resource kit?

Well, my quick answer would be: better having only one file to bring around instead of having dependencies with other files.

Fourth possible solution (my favourite!)

Another solution which does not have dependencies, does not have strange behaviours (like using ping), and works from Windows XP to Windows 8 is the following: use vbscript.

I know, I just wrote black on white that, if we can, it’s better not using any external file dependency, and infact, we won’t in this case.

A vbscript code for sleep is only a line of code which could be built in your batch and wrapped in a function like the following:

:sleep
SET vbs_sleep=%Temp%\sleep_%~1.vbs
IF NOT EXIST "%vbs_sleep%" > "%vbs_sleep%" ECHO WScript.Sleep %~1
CSCRIPT //NoLogo "%vbs_sleep%"
GOTO:EOF

The function can be used calling it like the following (e.g for 1 second sleep):

CALL:sleep 1000

Tags: , , , , ,

Category: Batch, Sistemi operativi, Windows

About the Author ()