How to sleep for five seconds in a batch file/cmd [duplicate]
Asked Answered
I

29

882

Windows's Snipping tool can capture the screen, but sometimes I want to capture the screen after five seconds, such as taking an image being displayed by the webcam. (Run the script and smile at the camera, for example.)

How do I sleep for 5 seconds in a batch file?

Italianate answered 4/11, 2009 at 8:13 Comment(8)
Quick answer for people landing here; there is a native solution since Windows Vista: TIMEOUT. Refs: SS64, Rob van der Woude.Putrescent
There is timeout command that waits for seconds. In case if millisecond sleep is needed, powershell's Start-Sleep can be used. To sleep 50ms in cmd: powershell Start-Sleep -m 50Krasner
@Pavel: You can also misuse a ping to a non-existent host to sleep for milliseconds.Muster
A good summary of the various techniques to halt a batch file process: robvanderwoude.com/wait.phpCabriole
Try This : timeout /t 5 /nobreak >nulGarnett
just for fun, if you have Node.js installed, you can use node -e 'setTimeout(a => a, 5000)' it works on a Mac with Node v12.14.0 and probably on Windows tooItalianate
Yet another option: powershell "Sleep 3"Dumdum
This solution works perfectly. C:\> timeout 5Britton
K
1010

One hack is to (mis)use the ping command:

ping 127.0.0.1 -n 6 > nul

Explanation:

  • ping is a system utility that sends ping requests. ping is available on all versions of Windows.
  • 127.0.0.1 is the IP address of localhost. This IP address is guaranteed to always resolve, be reachable, and immediately respond to pings.
  • -n 6 specifies that there are to be 6 pings. There is a 1s delay between each ping, so for a 5s delay you need to send 6 pings.
  • > nul suppress the output of ping, by redirecting it to nul.
Karankaras answered 4/11, 2009 at 8:20 Comment(13)
This doesn't work well for me (could be a networking issue)? When I try the above command (without the pipe to nul) I immediately get a "Destination host unreachable" from the gateway server and the ping command exits straight away.Artificial
It's cleaner and more reliable, IME, to do "ping 127.0.0.1 -n 10 > nul" - each ping waits 1s, so change the number of times to the number of seconds you wish to delay.Ranzini
One correction - 1.1.1.1 is a perfectly valid public IP address. Theoretically, it may be reached. It's offline now because I suspect their owners gave up hope to use it for anything but pings from all over the world :) For more details on this IP see serverfault.com/a/339782. It's saver to either use 127.0.0.1 as suggested by Cybergibbons, or one of the private addresses that don't exist in your network (e.g. 10.1.1.1, etc).Shavon
@Ranzini Beware fence-post error here. There is a 1s delay between each ping, so for a 10s delay you need to do 11 pings, i.e. "ping 127.0.0.1 -n 11 > nul"Foofaraw
II recommend to use 127.0.0.1 (localhost), if I have a problems with Internet, it isn't work :/Verecund
this tactic of using some ip like 1.1.1.1 may impact other network application when compounded with other app or task that does the same thing. timeout, or choice /T etc may be a better choice with far less likelyhood of interference on other task or apps.Exemption
Yes, use an IP address like 127.0.0.1 (or just the text "localhost"), which is valid. To use an invalid IP address causes ping to trip up the ERRORLEVEL.Peptidase
1.1.1.1 Is now owned by CloudFlare, so it'll certainly be reachable.Persiflage
This was basically edited until it plagiarises this answerHendeca
@GertvandenBerg There was only one edit that changed one line of code such that it is now similar (but still different) from the post you linked.Cotquean
@TylerH: The point of this answer (and all the comments on it) was to ping an "invalid" IP (which was actually perfectly valid but not assigned at that time) and use -w to delay it, not to ping localhost. In 2015 compie edited it with the same code as that answer.Hendeca
@GertvandenBerg It's not the same, just very similar. This is not to say I don't agree with the concern of changing the answer. I would recommend raising a question on Meta about what to do with this answer (e.g. roll it back completely? edit it to show the old code and update the explanation? leave it as it is?); there is no obvious choice either way.Cotquean
Since it was in a batch file I had to use @"C:\Windows\system32\ping" 127.0.0.1 -n %1% -w 1000 > nul (I don't recall why I added -w 1000!).Conchology
J
1817

I'm very surprised no one has mentioned:

C:\> timeout 5

N.B. Please note however (thanks Dan!) that timeout 5 means:

Sleep anywhere between 4 and 5 seconds

This can be verified empirically by putting the following into a batch file, running it repeatedly and calculating the time differences between the first and second echos:

@echo off
echo %time%
timeout 5 > NUL
echo %time%

Also note this, from the comments: timeout does not work in non-interactive scripts: "ERROR: Input redirection is not supported, exiting the process immediately." Daniel

Jenelljenelle answered 4/11, 2009 at 8:29 Comment(21)
'timeout' is not recognized as an internal or external command, operable program or batch file. (On my Windowx XP SP3)Cerement
it works on Win 7, but not on Win XPItalianate
I'm fairly certain I've used it on Server 2003 (same code base as XP), so it's a wonder it's not on XP then...Jenelljenelle
Because XP is not Server 2k3. Heck, it's two years older and historically (excluding NT 4) the server OSes came with some stuff that wasn't there in the workstation variant.Muster
timeout was introduce with Vista according to this site commandwindows.com/vista-tips.htm#timeoutPyrrhotite
found one in cygwin > which timeout > /usr/bin/timeoutAbbieabbot
Timeout is poorly implemented. If you do a "timeout 1", it will wait until the "next second," which could occur in .1 seconds. Try doing "timeout 1" a few times and observe the difference in delay. For 5 seconds or more, it may not be a big deal, but for a 1 second delay it works poorly.Hypersensitize
Also, you will likely want the '/nobreak' option. Otherwise, it finishes the timeout immediately on receiving a key press event.Ignacioignacius
It's not precise, but it works out of the box on Windows 8.Impulsion
timeout does not work in non-interactive scripts: "ERROR: Input redirection is not supported, exiting the process immediately."Ligula
@Hypersensitize so do not use 1 second use 2 seconds :DHalley
@Hypersensitize I'd also argue that, if that's how timeout is designed, it is not poorly implemented, it's just a poor solution to this problem! It might be useful in other circumstances to wait for the next second boundary...Haygood
@Haygood I'd argue that it's either poorly implemented or poorly documented if that's how it's designed. It specifically says in timeout /? that it will "wait for the specified time period (in seconds)". 0.1 second is a big difference from 1.0 and this has been a major thorn in my side and isn't something I can rely on for short(ish) timeoutsDipeptide
@AdamPlocher In that case, I'll retract my argument! :)Haygood
I am observing strange issue with timeout command, I have added 'timeout /t 275 /nobreak'. What I see is instead of 275 seconds, timeout is getting done in around 177 seconds. any ideas?Hirschfeld
not working in JENKINS: ERROR: Input redirection is not supported, exiting the process immediately.Precise
@Precise Consider using START /WAIT TIMEOUT /T x /NOBREAK >NUL for non-interactive scripts.Symposium
timeout not worked for me, even when used /NOBREAK command when caller is a C++ program. The ping workaround worked for that ...Lineberry
This answers the question of OP. Works in BAT file. Standard Windows, timeout.exe is in c:\windows\system32\ . (Win7) The manual is, as usual, in: timeout /?Rostock
pretty old, but just for completeness, while timeout DID work for me in a batch file executed from Windows 7 SP1 shell directly, when using Java and ProcessBuilder to run it it did not wait. ping solution, by the way, worked like a charm (which is the solution I was using before)Delastre
For those wondering that there is no "timeout" command in Windows XP: you are right, it is called "sleep" there.Veolaver
K
1010

One hack is to (mis)use the ping command:

ping 127.0.0.1 -n 6 > nul

Explanation:

  • ping is a system utility that sends ping requests. ping is available on all versions of Windows.
  • 127.0.0.1 is the IP address of localhost. This IP address is guaranteed to always resolve, be reachable, and immediately respond to pings.
  • -n 6 specifies that there are to be 6 pings. There is a 1s delay between each ping, so for a 5s delay you need to send 6 pings.
  • > nul suppress the output of ping, by redirecting it to nul.
Karankaras answered 4/11, 2009 at 8:20 Comment(13)
This doesn't work well for me (could be a networking issue)? When I try the above command (without the pipe to nul) I immediately get a "Destination host unreachable" from the gateway server and the ping command exits straight away.Artificial
It's cleaner and more reliable, IME, to do "ping 127.0.0.1 -n 10 > nul" - each ping waits 1s, so change the number of times to the number of seconds you wish to delay.Ranzini
One correction - 1.1.1.1 is a perfectly valid public IP address. Theoretically, it may be reached. It's offline now because I suspect their owners gave up hope to use it for anything but pings from all over the world :) For more details on this IP see serverfault.com/a/339782. It's saver to either use 127.0.0.1 as suggested by Cybergibbons, or one of the private addresses that don't exist in your network (e.g. 10.1.1.1, etc).Shavon
@Ranzini Beware fence-post error here. There is a 1s delay between each ping, so for a 10s delay you need to do 11 pings, i.e. "ping 127.0.0.1 -n 11 > nul"Foofaraw
II recommend to use 127.0.0.1 (localhost), if I have a problems with Internet, it isn't work :/Verecund
this tactic of using some ip like 1.1.1.1 may impact other network application when compounded with other app or task that does the same thing. timeout, or choice /T etc may be a better choice with far less likelyhood of interference on other task or apps.Exemption
Yes, use an IP address like 127.0.0.1 (or just the text "localhost"), which is valid. To use an invalid IP address causes ping to trip up the ERRORLEVEL.Peptidase
1.1.1.1 Is now owned by CloudFlare, so it'll certainly be reachable.Persiflage
This was basically edited until it plagiarises this answerHendeca
@GertvandenBerg There was only one edit that changed one line of code such that it is now similar (but still different) from the post you linked.Cotquean
@TylerH: The point of this answer (and all the comments on it) was to ping an "invalid" IP (which was actually perfectly valid but not assigned at that time) and use -w to delay it, not to ping localhost. In 2015 compie edited it with the same code as that answer.Hendeca
@GertvandenBerg It's not the same, just very similar. This is not to say I don't agree with the concern of changing the answer. I would recommend raising a question on Meta about what to do with this answer (e.g. roll it back completely? edit it to show the old code and update the explanation? leave it as it is?); there is no obvious choice either way.Cotquean
Since it was in a batch file I had to use @"C:\Windows\system32\ping" 127.0.0.1 -n %1% -w 1000 > nul (I don't recall why I added -w 1000!).Conchology
C
93

The following hack let's you sleep for 5 seconds

ping -n 6 127.0.0.1 > nul

Since ping waits a second between the pings, you have to specify one more than you need.

Cerement answered 4/11, 2009 at 8:20 Comment(3)
This should be -n 6. Otherwise you just wait 4 seconds. Remember that ping waits 1 second between pings, so you always have to specify one more try than you need.Muster
This is a much better solution than pinging a presumed non-existing IP, which by the way fails when network is down. Pinging localhost almost always works.Oleaceous
Should be > null if you're using powershell.Hangup
P
81

Try the Choice command. It's been around since MSDOS 6.0, and should do the trick.

Use the /T parameter to specify the timeout in seconds and the /D parameter to specify the default selection and ignore then selected choice.

The one thing that might be an issue is if the user types one of the choice characters before the timeout period elapses. A partial work-around is to obfuscate the situation -- use the /N argument to hide the list of valid choices and only have 1 character in the set of choices so it will be less likely that the user will type a valid choice before the timeout expires.

Below is the help text on Windows Vista. I think it is the same on XP, but look at the help text on an XP computer to verify.

C:\>CHOICE /?

CHOICE [/C choices] [/N] [/CS] [/T timeout /D choice] [/M text]

Description:
    This tool allows users to select one item from a list
    of choices and returns the index of the selected choice.

Parameter List:
   /C    choices       Specifies the list of choices to be created.
                       Default list is "YN".

   /N                  Hides the list of choices in the prompt.
                       The message before the prompt is displayed
                       and the choices are still enabled.

   /CS                 Enables case-sensitive choices to be selected.
                       By default, the utility is case-insensitive.

   /T    timeout       The number of seconds to pause before a default
                       choice is made. Acceptable values are from 0 to
                       9999. If 0 is specified, there will be no pause
                       and the default choice is selected.

   /D    choice        Specifies the default choice after nnnn seconds.
                       Character must be in the set of choices specified
                       by /C option and must also specify nnnn with /T.

   /M    text          Specifies the message to be displayed before
                       the prompt. If not specified, the utility
                       displays only a prompt.

   /?                  Displays this help message.

   NOTE:
   The ERRORLEVEL environment variable is set to the index of the
   key that was selected from the set of choices. The first choice
   listed returns a value of 1, the second a value of 2, and so on.
   If the user presses a key that is not a valid choice, the tool
   sounds a warning beep. If tool detects an error condition,
   it returns an ERRORLEVEL value of 255. If the user presses
   CTRL+BREAK or CTRL+C, the tool returns an ERRORLEVEL value
   of 0. When you use ERRORLEVEL parameters in a batch program, list
   them in decreasing order.

Examples:
   CHOICE /?
   CHOICE /C YNC /M "Press Y for Yes, N for No or C for Cancel."
   CHOICE /T 10 /C ync /CS /D y
   CHOICE /C ab /M "Select a for option 1 and b for option 2."
   CHOICE /C ab /N /M "Select a for option 1 and b for option 2."
Pyrrhotite answered 5/5, 2010 at 18:48 Comment(4)
it is not on XP either...Italianate
that's interesting. This site computerhope.com/choicehl.htm states that choice is available on Windows 95, Windows 98, Windows Vista and Windows 7, but not Windows XP. I bet that MS got a lot of complaints about taking it of XP, so put they put it back into Vista.Pyrrhotite
I'm using CHOICE on Vista. Works fine.Minor
The command is greate, but unfortunally not native in windows XP. But you can simply copy the choice.com from your windows 98 System-directory, it works fine in windows xp.Amphibole
S
61

If you've got PowerShell on your system, you can just execute this command:

powershell -command "Start-Sleep -s 5"

Edit: people raised an issue where the amount of time powershell takes to start is significant compared to how long you're trying to wait for. If the accuracy of the wait time is important (ie a second or two extra delay is not acceptable), you can use this approach:

powershell -command "$sleepUntil = [DateTime]::Parse('%date% %time%').AddSeconds(5); $sleepDuration = $sleepUntil.Subtract((get-date)).TotalMilliseconds; start-sleep -m $sleepDuration"

This takes the time when the windows command was issued, and the powershell script sleeps until 5 seconds after that time. So as long as powershell takes less time to start than your sleep duration, this approach will work (it's around 600ms on my machine).

Selffertilization answered 29/5, 2013 at 0:0 Comment(8)
Simply loading up PowerShell takes a few seconds.Laevogyrate
Well 600ms isn’t too bad, but that’s on your OS on your hardware. PowerShell takes about six seconds to load on XP the first time it is run in a Windows session, then about three seconds for subsequent runs. In Windows 7 on the same system, it takes less and on a faster system even less. In short, this isn’t a very portable solution.Laevogyrate
Did you try the alternate solution I pasted?Selffertilization
It doesn't have any protection from the case where the powershell startup lag is longer than the sleep duration, but that would be easy enough to addSelffertilization
I ended up using this myself. Running the plain 5 second sleep takes about 5.5 seconds - 5.6 seconds to complete on my machine. Using the second script I posted gets the inaccuracy down to around 20 - 30 milliseconds. If you need more accuracy than this, I doubt you'll get it from the ping approach either.Selffertilization
@NiallConnaughton Can you test with –NoProfile and see how much that affects the speed? This avoids loading the user's profile which should prevent a disk search and file access as well as any "plugins/modules/etc" that get added to the user's profile.Worried
Apparently there are 6 potential profiles that PowerShell will try to load if you don't pass -NoProfile. blogs.technet.microsoft.com/heyscriptingguy/2012/05/21/…Worried
On my current system, there's a 150ms cost to starting powershell, and -noprofile isn't improving that. However, this machine is not on a corporate domain with a roaming profile, etc. YMMV. Good suggestion.Selffertilization
S
50

You can make it with timeout:

This will be visible: timeout 5

This will not be visible timeout 5 >nul

Shavon answered 3/3, 2014 at 16:59 Comment(2)
timeout command available in win 7, but not in win xp.Ephemerality
note that even though not visible it will still get cancelled if the user presses a key, add /NOBREAK option to prevent thatPreshrunk
A
40

Can't we do waitfor /T 180?

waitfor /T 180 pause will result in "ERROR: Timed out waiting for 'pause'."

waitfor /T 180 pause >nul will sweep that "error" under the rug

The waitfor command should be there in Windows OS after Win95

In the past I've downloaded a executable named sleep that will work on the command line after you put it in your path.

For example: sleep shutdown -r -f /m \\yourmachine although shutdown now has -t option built in

Acinus answered 31/10, 2012 at 18:14 Comment(5)
Wasn't present on my XP Pro SP3 machine, but it was on Win7 Ultimate machine.Sforza
waitfor is for waiting for a signal. Not sure how to use it, but it doesn't seem to fit the bill.Seasickness
waitfor /T 10 pause works pretty well.Ecclesiastic
@SchlaWiener that's what worked for me, added it to the answer directlySeraph
You can use 2> to eat the error waitfor /T 5 pause 2>NULEnervated
B
36

Timeout /t 1 >nul

Is like pause in 1 secound, you can take the limed to almost 100.000 (99.999) secounds. If you are connected to the internet the best solution would be:

ping 1.1.1.1. -n 1 -w 1000 >nul

When you ping you count in milliseconds, so one second would be 1000 milliseconds. But the ping command is a little iffy, it does not work the same way on offline machines. The problem is that the machine gets confused because it is offline, and it would like to ping a website/server/host/ip, but it can't. So i would recommend timeout. Good luck!

Byers answered 28/7, 2013 at 13:26 Comment(5)
Pinging to 1.1.1.1 is not a good and really not the best solution. It causes network traffic. Ping to localhost instead.Tonometer
The point of pinging an unreachable IP address is to cause the command to wait for a response and timeout after the specified time. "localhost" is likely to reply rather than timeout on most systems.Chill
@user3070485 But 1.1.1.1 is not unreachable. Why not use something like 192.0.2.1, which is guaranteed to be unreachable?Himelman
1.1.1.1 used to be unreachable @Tijmen. I've seen it used many times as a very bad example of an "unreachable" address.Pacificism
I shudder to think of all the scripts that suddenly broke when Cloudflare started responding to pings on 1.1.1.1.Crystallization
G
35

SLEEP 5 was included in some of the Windows Resource Kits.

TIMEOUT 5 was included in some of the Windows Resource Kits, but is now a standard command in Windows 7 and 8 (not sure about Vista).

PING 1.1.1.1 -n 1 -w 5000 >NUL For any MS-DOS or Windows version with a TCP/IP client, PING can be used to delay execution for a number of seconds.

NETSH badcommand (Windows XP/Server 2003 only) or CHOICE

this link will help you more.

Gardie answered 19/2, 2016 at 20:45 Comment(1)
Sorry, but I have to downvote an answer that assumes the unreachability of 1.1.1.1.Crystallization
S
29

There is!

SLEEP <seconds>

If you want it in millisecond mode:

SLEEP -m <time in milliseconds>

This is more helpful than TIMEOUT because TIMEOUT can be aborted with a click of a key or CTRL + C (for TIMEOUT /t <secs> /nobreak). SLEEP cannot be aborted by anything (except for close button :p)

Other one is PING. But PING needs internet connection because you'll be recording the connection of a site.

Sumach answered 28/12, 2017 at 2:10 Comment(6)
There IS a sleep command in vanilla windows. It solely depends on which edition of Windows you're running. This is native to Windows 7 Pro/Enterprise, Windows 10 Pro/Enterprise, All Windows Server 2008+ editions. I have upvoted this as it is a valid solution.Creek
@TimothyWood I'm running Server 2012 R2 and SLEEP is not available. The answer should provide accurate information on what version(s) of windows it works on.Goddamned
Some versions that don't have SLEEP available have TIMEOUT available. TIMEOUT /T <seconds> /NOBREAKGoddamned
@Goddamned Sleep is a native command. It just depends on what features and roles you have included in the configuration of your server. To specifically get access to the sleep command, install the 2003 Windows Resource Kit. This automatically installed by enabling one among the few features that require it in the Server Manager. It's also a prerequisite that's included with Visual Studio. The answer was accurate. Not having the sleep command is not the same as not knowing what commands can be used and therefore it's an entirely separate issue.Creek
Windows 10 has TIMEOUT (with the option to shorten the wait by pressing a key, btw), but no SLEEPStanford
no sleep on win11 eitherDiffusion
A
19

Two answers:

Firstly, to delay in a batch file, simply without all the obtuse methods people have been proposing:

timeout /t <TimeoutInSeconds> [/nobreak] 

http://technet.microsoft.com/en-us/library/cc754891.aspx

Secondly, worth mentioning that while it may not do exactly what you want, using the inbuilt Windows snipping tool, you can trigger a snip on it without using the mouse. Run the snipping tool, escape out of the current snip but leave the tool running, and hit Control + Print Screen when you want the snip to occur. This shouldn't interfere with whatever it is you're trying to snip.

Amphitheater answered 12/7, 2014 at 2:3 Comment(0)
H
16

I was trying to do this from within an msbuild task, and choice and timeout both did not work due to I/O redirection.

I ended up using sleep.exe from http://sourceforge.net/projects/unxutils, which is nice because it doesn't require any install and it's tiny.


Trying with choice:

<Target Name="TestCmd">
  <Exec Command="choice /C YN /D Y /t 5 " />
</Target>

Results in:

TestCmd:
  choice /C YN /D Y /t 5

EXEC : error : The file is either empty or does not contain the valid choices. [test.proj]
  [Y,N]?
C:\test.proj(5,9): error MSB3073: The command "choice /C YN /D Y /t 5 " exited with code 255.

Trying with timeout:

<Target Name="TestCmd">
  <Exec Command="timeout /t 5 " />
</Target>

Results in:

TestCmd:
  timeout /t 5
EXEC : error : Input redirection is not supported, exiting the process immediately. [test.proj]
C:\test.proj(5,7): error MSB3073: The command "timeout /t 5 " exited with code 1.

Aside:

I am actually using <Exec Command="sleep 2 & dbghost.exe" /> because I am executing dbghost.exe multiple times in parallel and it creates temp files/databases based on the current epoch time in seconds - which of course means if you start multiple instances, each uses the same temp name. I was originally trying to use MSBuild Extension Pack Thread.Sleep command, but it seems that (usually) it was running the sleep task fine, but then starting the <exec> task in all threads at the same time, and of course dbghost.exe would fail with conflicts. So far, using sleep.exe seems to be more reliable.

Hyps answered 5/11, 2012 at 21:1 Comment(3)
Extremely helpful note about choice/timeout not working within an msbuild task. In that case I did find the accepted answer (ping) worked for me within msbuild: ping 1.1.1.1 -n 1 -w 3000 > nulGranniah
Also choice/timeout does not work in an Ant task either.Fp
FOR BUILD SERVERS! CHOICE and TIMEOUT don't work under a non-interactive process/account. Forget about them on build-machines. PING 1.1.1.1 doesn't work if your network connection fails. Look around here for W32TM, TypePerf, some PowerShell. Or create your custom .NET executable.Hartle
L
13

Two more ways that should work on everything from XP and above:

with w32tm:

w32tm /stripchart /computer:localhost /period:5 /dataonly /samples:2  1>nul 

with typeperf:

typeperf "\System\Processor Queue Length" -si 5 -sc 1 >nul

with mshta (does not require set up network):

start "" /w /b /min mshta "javascript:setTimeout(function(){close();},5000);"
Laudanum answered 22/10, 2015 at 16:36 Comment(1)
These are tested! Your TypePerf and TYPEPERF commands work when a network connection is broken.Hartle
C
9

This is the latest version of what I am using in practice for a ten second pause to see the output when a script finishes.

BEST>@echo done
BEST>@set DelayInSeconds=10
BEST>@rem Use ping to wait
BEST>@ping 192.0.2.0 -n 1 -w %DelayInSeconds%000 > nul

The echo done allows me to see when the script finished and the ping provides the delay. The extra @ signs mean that I see the "done" text and the waiting occurs without me being distracted by their commands.

I have tried the various solutions given here on an XP machine, since the idea was to have a batch file that would run on a variety of machines, and so I picked the XP machine as the environment likely to be the least capable.

GOOD> ping 192.0.2.0 -n 1 -w 3000 > nul

This seemed to give a three second delay as expected. One ping attempt lasting a specified 3 seconds.

BAD> ping -n 5 192.0.2.0 > nul

This took around 10 seconds (not 5). My explanation is that there are 5 ping attempts, each about a second apart, making 4 seconds. And each ping attempt probably lasted around a second making an estimated 9 seconds in total.

BAD> timeout 5
BAD> sleep /w2000
BAD> waitfor /T 180
BAD> choice

Commands not available.

BAD> ping 192.0.2.0 -n 1 -w 10000 > nul :: wait 10000 milliseconds, ie 10 secs

I tried the above too, after reading that comments could be added to BAT files by using two consecutive colons. However the software returned almost instantly. Putting the comment on its own line before the ping worked fine.

GOOD> :: wait 10000 milliseconds, ie 10 secs
GOOD> ping 192.0.2.0 -n 1 -w 10000 > nul

To understand better what ping does in practice, I ran

ping 192.0.2.0 -n 5 -w 5000

This took around 30 seconds, even though 5*5=25. My explanation is that there are 5 ping attempts each lasting 5 seconds, but there is about a 1 second time delay between ping attempts: there is after all little reason to expect a different result if you ping again immediately and it is better to give a network a little time to recover from whatever problem it has had.

Edit: stolen from another post, .. RFC 3330 says the IP address 192.0.2.0 should not appear on the internet, so pinging this address prevents these tests spamming anyone! I have modified the text above accordingly!

Chill answered 18/9, 2014 at 9:7 Comment(2)
About comments in cmd batch files: Comments should start with the REM command. See https://mcmap.net/q/47925/-how-do-i-comment-on-the-windows-command-line. The double colon is actually a misused label which is ignored by the command processor. It works as a comment if used on a line of its own, but beware: if used inside IF statements, it will mess up the execution flow.Mas
There are 2 approaches to using the ping command: 1. pinging an existing address (127.0.0.1) or a non-existing one (192.0.2.0). The existing one will reply in less than a millisecond, so you ping n+1 times for an n-second delay. The non-existing one will timeout, so you need to set the timeout value to n*1000 for an n-second delay.Mas
A
6

I made this. It is working and show time left in seconds. If you want to use it, add to a batch file:

call wait 10

It was working when I tested it.

Listing of wait.bat (it must be in the working directory or windir/system32/):

@echo off

set SW=00

set SW2=00

set /a Sec=%1-1

set il=00
@echo Wait %1 second
for /f "tokens=1,2,3,4 delims=:," %%A in ("%TIME%") do set /a HH=%%A, MM=1%%B-100, SS=1%%C-100, CC=1%%D-100, TBASE=((HH*60+MM)*60+SS)*100+CC, SW=CC 

set /a TFIN=%TBASE%+%100

:ESPERAR
for /f "tokens=1,2,3,4 delims=:," %%A in ("%TIME%") do set /a HH=%%A, MM=1%%B-100, SS=1%%C-100, 

CC=1%%D-100, TACTUAL=((HH*60+MM)*60+SS)*100+CC,  SW2=CC


if %SW2% neq %SW% goto notype
if %il%==0 (echo Left %Sec% second & set /a Sec=sec-1 & set /a il=il+1)
goto no0
:notype
set /a il=0
:no0

if %TACTUAL% lss %TBASE% set /a TACTUAL=%TBASE%+%TACTUAL%
if %TACTUAL% lss %TFIN% goto ESPERAR
Anglofrench answered 7/12, 2012 at 3:31 Comment(0)
A
5

You can use VBScript, for example, file myscript.vbs:

set wsobject = wscript.createobject("wscript.shell")

do while 1=1
    wsobject.run "SnippingTool.exe",0,TRUE
    wscript.sleep 3000
loop

Batch file:

cscript myscript.vbs %1
Amoretto answered 4/11, 2009 at 8:19 Comment(1)
why the %1? you didn't put any place for arguments in the code. I use this: sleep.vbs: wscript.sleep wscript.arguments(1)Doughman
I
5

An improvement of the code proposed by the user Aacini, It has resolution of hundredths of a second and does not fail when the time reaches 23:59:59,99:

for /f "tokens=1,2,3,4 delims=:," %%A in ("%TIME%") do set /a HH=%%A, MM=1%%B-100, SS=1%%C-100, CC=1%%D-100, TBASE=((HH*60+MM)*60+SS)*100+CC

:: Example delay 1 seg.
set /a TFIN=%TBASE%+100

:ESPERAR
for /f "tokens=1,2,3,4 delims=:," %%A in ("%TIME%") do set /a HH=%%A, MM=1%%B-100, SS=1%%C-100, CC=1%%D-100, TACTUAL=((HH*60+MM)*60+SS)*100+CC

if %TACTUAL% lss %TBASE% set /a TACTUAL=%TBASE%+%TACTUAL%
if %TACTUAL% lss %TFIN% goto ESPERAR
Indira answered 4/11, 2012 at 19:14 Comment(0)
S
4

I use the following method entirely based on Windows XP capabilities to do a delay in a batch file:

File DELAY.BAT

@ECHO OFF
REM DELAY seconds

REM GET ENDING SECOND
FOR /F "TOKENS=1-3 DELIMS=:." %%A IN ("%TIME%") DO SET /A H=%%A, M=1%%B%%100,     S=1%%C%%100, ENDING=(H*60+M)*60+S+%1

REM WAIT FOR SUCH A SECOND
:WAIT
FOR /F "TOKENS=1-3 DELIMS=:." %%A IN ("%TIME%") DO SET /A H=%%A, M=1%%B%%100, S=1%%C%%100, CURRENT=(H*60+M)*60+S
IF %CURRENT% LSS %ENDING% GOTO WAIT

You may also insert the day in the calculation so the method also works when the delay interval pass over midnight.

Serenity answered 24/7, 2011 at 10:19 Comment(1)
This is a "busy wait" and so may do undesirable things to your machine's performance. Check task manager while it's running to see effect on CPU usage.Fragile
R
4

The easiest way I did it was this:

Download the Sleep.exe at http://www.sleepcmd.com/. The .exe file should be in the same folder as the program you wrote!

Resolved answered 11/12, 2012 at 7:2 Comment(1)
if downloading an exe was the right answer, sleep.exe from the ms rk would be a better choice. And putting it in the path.Doughman
M
4

It can be done with two simple lines in a batch file: write a temporary .vbs file in the %temp% folder and call it:

echo WScript.Sleep(5000) >"%temp%\sleep.vbs"
cscript "%temp%\sleep.vbs"
Merrygoround answered 17/6, 2013 at 18:53 Comment(0)
O
3

If you have an appropriate version of Windows and the Windows Server 2003 Resource Kit Tools, it includes a sleep command for batch programs. More at: http://malektips.com/xp_dos_0002.html

Ombre answered 5/5, 2010 at 19:6 Comment(0)
H
3
PING -n 60 127.0.0.1>nul

in case your LAN adapter is not available.

Henceforward answered 29/4, 2014 at 7:13 Comment(0)
T
1

In Windows xp sp3 you can use sleep command

Territus answered 27/6, 2014 at 18:16 Comment(1)
I suggest to stop using XP: Extended support for Windows XP ended on April 8, 2014, after which the operating system ceased receiving further support or security updates to most users. As of March 2019, 1.75% of Windows PCs run Windows XP,[7] and the OS is still most popular in some countries with up to 38% of the Windows share.[8] (wikipedia)Pash
V
1

Make a cmd file called sleep.cmd:

REM Usage: SLEEP Time_in_MiliSECONDS
@ECHO off
ping 1.0.0.0 -n 1 -w %1 > nul

Copy sleep.cmd to c:\windows\system32

Usage:

sleep 500

Sleeps for 0.5 seconds. Arguments in ms. Once copied to System32, can be used everywhere.

EDIT: You should also be away that if the machine isn't connected to a network (say a portable that your using in the subway), the ping trick doesn't really work anymore.

Vicentevicepresident answered 25/3, 2016 at 1:57 Comment(6)
This is a potentially interesting alternative to the other ping examples but you need to explain it more. Why do you choose to ping 1.0.0.0?Airflow
Probably no specific reason. Using 127.0.0.1 is a safer bet as explained in other commentsNegress
It could be 127.0.0.1. I just choose 1.0.0.0 so if I distribute a batch script, it doesn't look like I'm trying to ping myself if someone reads it. Why is 127.0.0.1 a safer bet?Vicentevicepresident
why should it not look like you are trying to ping yourself? 1.0.0.0 seems more silly to try to ping.But the more important part is, -w will not have any effect unless you set -n 2. -w specifies wait between packages, and with one package there is no "between"Pardon
strange, it worked for me without the -n. Though it doesn't seem work if you're running it without being connected to some kind of network. Personally, I don't really use the ping technique to pause anymore because of that reason. As for the address, you can ping whatever you want, it's really not relevant.Vicentevicepresident
Note that there are two ping techniques being used in the replies. Ping a known working address, and ping a known failing address. A single 5 second ping to a failing address e.g. 192.0.2.0 will time for 5 seconds. Alternatively 6 successful pings a second apart to a working address e.g. 127.0.0.1 will time for 5 seconds plus the length of the 6 pings.I think there is confusion about the two techniques in the comments above.Chill
G
0

Well this works if you have choice or ping.

@echo off
echo.
if "%1"=="" goto askq
if "%1"=="/?" goto help
if /i "%1"=="/h" goto help
if %1 GTR 0 if %1 LEQ 9999 if /i "%2"=="/q" set ans1=%1& goto quiet
if %1 GTR 0 if %1 LEQ 9999 set ans1=%1& goto breakout
if %1 LEQ 0 echo %1 is not a valid number & goto help
if not "%1"=="" echo.&echo "%1" is a bad parameter & goto help
goto end

:help
echo SLEEP runs interactively (by itself) or with parameters (sleep # /q )
echo where # is in seconds, ranges from 1 - 9999
echo Use optional parameter /q to suppress standard output 
echo or type /h or /? for this help file
echo.
goto end

:askq
set /p ans1=How many seconds to sleep? ^<1-9999^> 
echo.
if "%ans1%"=="" goto askq
if %ans1% GTR 0 if %ans1% LEQ 9999 goto breakout
goto askq

:quiet
choice /n /t %ans1% /d n > nul
if errorlevel 1 ping 1.1.1.1 -n 1 -w %ans1%000 > nul
goto end

:breakout
choice /n /t %ans1% /d n > nul
if errorlevel 1 ping 1.1.1.1 -n 1 -w %ans1%000 > nul
echo Slept %ans1% second^(s^)
echo.

:end

just name it sleep.cmd or sleep.bat and run it

Gott answered 19/4, 2012 at 21:10 Comment(0)
M
0

ping waits for about 5 seconds before timing out, not 1 second as was stated above. That is, unless you tell it to only wait for 1 second before timing out.

ping 1.0.0.1 -n 1 -w 1000

will ping once, wait only 1 second (1000 ms) for a response, then time out.

So an approximately 20-second delay would be:

ping 1.0.0.1 -n 20 -w 1000

Magistracy answered 26/1, 2016 at 23:45 Comment(3)
The accepted answer describes it already, and Jonathan already showed your solution of using an invalid IP addressWerbel
Also, if the pings last a second (waiting for a response that doesn't happen) and are a second apart - as there is no point repeating a failure immediately - then your approximate 20 second delay will be closer to 39 seconds. By copying the accepted answer, you also copy its mistakes!Chill
The current time is: 10:00:03.80 (RUN YOUR 20 SECOND DELAY) The current time is: 10:00:45.96 That's not what I call a 20s delay!Chill
W
0

I wrote a powerbasic program wait.exe, where you pass a millisecond parameter to it in your batch file

wait 3000
system('c:/windows/system32/SnippingTool.exe')

the code for the EXE:

FUNCTION PBMAIN()
  c$ = Command$
  s! = Val(c$)*1000
  Sleep s!         
END FUNCTION
Williswillison answered 6/6, 2017 at 15:35 Comment(0)
U
-2

On newer Windows OS versions you can use the command

sleep /w2000

in a DOS script (.cmd or .bat) to wait for 2s (2000 ms - substitute the time in ms you need). Be careful to include the /w argument - without it the whole computer is put to sleep! You can use -m instead of /m if you wish and optionally a colon (:) between the w and the number.

Unger answered 15/5, 2013 at 9:42 Comment(4)
Define “newer Windows”.Laevogyrate
Newer than win7 apparently ;)Fragile
It's not even on Windows 10. I thought a 'sleep' existed too, but apparently 'timeout' is the command to use.Indifference
Please test your solution and report which version of Windows and where sleep.exe comes from.Worried
A
-4

I think the following command can help:

pause 5

The syntax of the pause command is: pause d \\where d represents the duration in seconds

I am using Windows 7 (32 bit), but I don't know about the others.

Auroora answered 17/3, 2013 at 17:43 Comment(4)
On WinXP is does not work like that. It waits for infinity, ignoring the argument.Hillie
The purpose of pause is to, "Suspends processing of a batch program and displays the message Press any key to continue . . ."Rocky
Nope, not on win 7, you must have some non-standard utilities installed.Fragile
Available on all Windows releases according to computerhope.com/pausehlp.htm. Note thought it is not available on command-line, only inside batch files..Ripp

© 2022 - 2024 — McMap. All rights reserved.