Wednesday, April 20, 2011

How to wait in a batch script

I am trying to write a batch script and trying to wait 10 seconds between 2 Function calls.

sleep 10

does not wait for 10 seconds

I am running XP

From stackoverflow
  • You can ping a random address and specify the desired timeout:

    ping 123.45.67.89 -n 1 -w 10000 > nul
    

    And since the address does not exists, it'll wait 10,000 ms (10 seconds) and returns.


    • The -w 10000 part specifies the desired timeout in milliseconds.
    • The -n 1 part tells ping that it should only tries once (normally it'd try 4 times).
    • The > nul part is appended so the ping command doesn't output anything to screen.

    You can easily make a sleep command yourself by creating a sleep.bat somewhere in your PATH and use the above technique:

    rem SLEEP.BAT - sleeps by the supplied number of seconds
    
    @ping 123.45.67.89 -n 1 -w %1000 > nul
    

    ...

    ojblass : Hack -2 Genius +3
    Paul Tomblin : That's so crazy it might work.
    Thomaschaaf : ping 127.0.0.1 -n 5 -w 1000 > nul hat to do it like this since the other would finish right away.
    chakrit : @Thomaschaaf interesting... pinging a local machine address should've caused ping to return *right away* since it's pinging the same machine (i.e. time<1ms) so the timeout trick shouldn't have worked in that case!
    Thomaschaaf : I added the actual function its called timeout.. http://www.ss64.com/nt/timeout.html at least I know that others didn't know either :)
  • Well, does sleep even exist on your xp box? According to this post: http://malektips.com/xp_dos_0002.html sleep isn't available on windows xp and you have to download the windows 2003 resource kit in order to get it.

    Chakrit's answer gives you another way to pause, too.

    Try running sleep 10 from a command prompt.

  • You'd better ping 127.0.0.1. Windows ping pauses for one second between pings so you if you want to sleep for 10 seconds, use

    ping -n 11 127.0.0.1 > nul
    

    This way you don't need to worry about unexpected early returns (say, there's no default route and the 123.45.67.89 is instantly known to be unreachable.)

  • I actually found the right command to use.. its called timeout: http://www.ss64.com/nt/timeout.html

    Thomaschaaf : alternative would be chakrits http://www.ss64.com/nt/sleep.html
    Romulo A. Ceccon : Also not a Windows XP command...
  • this blog post has a number of ideas on how to best do this:

    http://notetodogself.blogspot.com/2007/11/wait-in-windows-bat-script-good-way.html

  • I used this

    :top
    cls
    type G:\empty.txt
    type I:\empty.txt
    timeout /T 500
    goto top
    
  • what about :

    @echo off

    set wait=%1

    echo waiting %wait% s

    echo wscript.sleep %wait%000 > wait.vbs

    wscript.exe wait.vbs

    del wait.vbs

  • Hi I decided to write sleep for my own. Check out my homepage http://www.marcindabrowski.net/?p=122

0 comments:

Post a Comment