标签归档:batch-file

睡眠在批处理文件中

问题:睡眠在批处理文件中

编写批处理文件以自动执行Windows框上的某些操作时,我需要将其执行暂停几秒钟(通常在测试/等待循环中,等待进程启动)。当时,我能找到的最佳解决方案是使用ping(我不告诉你)来达到预期的效果。我已经找到了更好的写了它在这里,它描述了一个可调用“wait.bat”,实现如下:

@ping 127.0.0.1 -n 2 -w 1000 > nul
@ping 127.0.0.1 -n %1% -w 1000> nul

然后,您可以在自己的批处理文件中包含对wait.bat的调用,传递进入睡眠的秒数。

显然Windows 2003 Resource Kit提供了一个类似Unix的sleep命令(最后!)。同时,对于仍然使用Windows XP,Windows 2000或(不幸的)Windows NT的我们来说,还有更好的方法吗?

sleep.py接受的答案中修改了脚本,以便如果在命令行上未传递任何参数,则默认为一秒钟:

import time, sys

time.sleep(float(sys.argv[1]) if len(sys.argv) > 1 else 1)

When writing a batch file to automate something on a Windows box, I’ve needed to pause its execution for several seconds (usually in a test/wait loop, waiting for a process to start). At the time, the best solution I could find uses ping (I kid you not) to achieve the desired effect. I’ve found a better write-up of it here, which describes a callable “wait.bat”, implemented as follows:

@ping 127.0.0.1 -n 2 -w 1000 > nul
@ping 127.0.0.1 -n %1% -w 1000> nul

You can then include calls to wait.bat in your own batch file, passing in the number of seconds to sleep.

Apparently the Windows 2003 Resource Kit provides a Unix-like sleep command (at last!). In the meantime, for those of us still using Windows XP, Windows 2000 or (sadly) Windows NT, is there a better way?

I modified the sleep.py script in the accepted answer, so that it defaults to one second if no arguments are passed on the command line:

import time, sys

time.sleep(float(sys.argv[1]) if len(sys.argv) > 1 else 1)

回答 0

更新

timeout命令,可以从Windows Vista和以后应在命令中使用,如在另一所描述的回答了这个问题。接下来是一个古老的答案。

旧答案

如果您安装了Python,或者不介意安装它(它也具有其他用途:),只需创建以下sleep.py脚本并将其添加到PATH中的某个位置即可:

import time, sys

time.sleep(float(sys.argv[1]))

如果您有此需要,它将允许亚秒级的暂停(例如1.5秒,0.1等)。如果您希望将其称为sleep而不是sleep.py,则可以将.PY扩展名添加到PATHEXT环境变量中。在Windows XP上,您可以在以下位置进行编辑:

我的电脑→属性(菜单)→高级(选项卡)→环境变量(按钮)→系统变量(框架)

UPDATE

The timeout command, available from Windows Vista and onwards should be the command used, as described in another answer to this question. What follows here is an old answer.

Old answer

If you have Python installed, or don’t mind installing it (it has other uses too :), just create the following sleep.py script and add it somewhere in your PATH:

import time, sys

time.sleep(float(sys.argv[1]))

It will allow sub-second pauses (for example, 1.5 sec, 0.1, etc.), should you have such a need. If you want to call it as sleep rather than sleep.py, then you can add the .PY extension to your PATHEXT environment variable. On Windows XP, you can edit it in:

My Computer → Properties (menu) → Advanced (tab) → Environment Variables (button) → System variables (frame)


回答 1

timeout从Windows Vista以后的版本中可以使用该命令:

c:\> timeout /?

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

注意:它不适用于输入重定向-简单示例:

C:\>echo 1 | timeout /t 1 /nobreak
ERROR: Input redirection is not supported, exiting the process immediately.

The timeout command is available from Windows Vista onwards:

c:\> timeout /?

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

Note: It does not work with input redirection – trivial example:

C:\>echo 1 | timeout /t 1 /nobreak
ERROR: Input redirection is not supported, exiting the process immediately.

回答 2

ping当无法(或不想)添加更多可执行文件或安装任何其他软件时,如何使用概述的方法。

你应该查验的东西是不存在的,并使用-w标志,以便它的时间量之后出现故障,无法查验的东西,有(如本地主机)-n倍。这使您可以处理不到一秒钟的时间,而且我认为它稍微更准确。

例如

(测试未采用1.1.1.1)

ECHO Waiting 15 seconds

PING 1.1.1.1 -n 1 -w 15000 > NUL
  or
PING -n 15 -w 1000 127.1 >NUL

Using the ping method as outlined is how I do it when I can’t (or don’t want to) add more executables or install any other software.

You should be pinging something that isn’t there, and using the -w flag so that it fails after that amount of time, not pinging something that is there (like localhost) -n times. This allows you to handle time less than a second, and I think it’s slightly more accurate.

e.g.

(test that 1.1.1.1 isn’t taken)

ECHO Waiting 15 seconds

PING 1.1.1.1 -n 1 -w 15000 > NUL
  or
PING -n 15 -w 1000 127.1 >NUL

回答 3

SLEEP.exe包含在大多数资源工具包中,例如Windows Server 2003资源工具包,也可以安装在Windows XP上。

Usage:  sleep      time-to-sleep-in-seconds
        sleep [-m] time-to-sleep-in-milliseconds
        sleep [-c] commited-memory ratio (1%-100%)

SLEEP.exe is included in most Resource Kits e.g. The Windows Server 2003 Resource Kit which can be installed on Windows XP too.

Usage:  sleep      time-to-sleep-in-seconds
        sleep [-m] time-to-sleep-in-milliseconds
        sleep [-c] commited-memory ratio (1%-100%)

回答 4

我不同意我在这里找到的答案。

我完全基于Windows XP功能使用以下方法在批处理文件中进行延迟:

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

您也可以在计算中插入日期,这样,当延迟间隔超过午夜时,该方法也将起作用。

I disagree with the answers I found here.

I use the following method entirely based on Windows XP capabilities to do a delay in a batch 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.


回答 5

我遇到了类似的问题,但是我只是关闭了一个很短的C ++控制台应用程序来做同样的事情。只需运行MySleep.exe 1000,这可能比下载/安装整个资源工具包容易。

#include <tchar.h>
#include <stdio.h>
#include "Windows.h"

int _tmain(int argc, _TCHAR* argv[])
{
    if (argc == 2)
    {
        _tprintf(_T("Sleeping for %s ms\n"), argv[1]);
        Sleep(_tstoi(argv[1]));
    }
    else
    {
        _tprintf(_T("Wrong number of arguments.\n"));
    }
    return 0;
}

I faced a similar problem, but I just knocked up a very short C++ console application to do the same thing. Just run MySleep.exe 1000 – perhaps easier than downloading/installing the whole resource kit.

#include <tchar.h>
#include <stdio.h>
#include "Windows.h"

int _tmain(int argc, _TCHAR* argv[])
{
    if (argc == 2)
    {
        _tprintf(_T("Sleeping for %s ms\n"), argv[1]);
        Sleep(_tstoi(argv[1]));
    }
    else
    {
        _tprintf(_T("Wrong number of arguments.\n"));
    }
    return 0;
}

回答 6

在服务器故障处,提出了类似的问题,解决方案是:

choice /d y /t 5 > nul

Over at Server Fault, a similar question was asked, and the solution there was:

choice /d y /t 5 > nul

回答 7

您可以使用Windows cscript WSH层和以下wait.js JavaScript文件:

if (WScript.Arguments.Count() == 1)
    WScript.Sleep(WScript.Arguments(0)*1000);
else
    WScript.Echo("Usage: cscript wait.js seconds");

You could use the Windows cscript WSH layer and this wait.js JavaScript file:

if (WScript.Arguments.Count() == 1)
    WScript.Sleep(WScript.Arguments(0)*1000);
else
    WScript.Echo("Usage: cscript wait.js seconds");

回答 8

根据您的兼容性需求,可以使用ping

ping -n <numberofseconds+1> localhost >nul 2>&1

例如等待5秒钟,使用

ping -n 6 localhost >nul 2>&1

或在Windows 7或更高版本上使用timeout

timeout 6 >nul

Depending on your compatibility needs, either use ping:

ping -n <numberofseconds+1> localhost >nul 2>&1

e.g. to wait 5 seconds, use

ping -n 6 localhost >nul 2>&1

or on Windows 7 or later use timeout:

timeout 6 >nul

回答 9

您可以使用ping:

ping 127.0.0.1 -n 11 -w 1000 >nul: 2>nul:

它将等待10秒钟。

您必须使用11的原因是因为第一次ping立即发出,而不是一秒钟后发出。该数字应始终比您要等待的秒数大一。

请记住,的目的-w不是等待一秒钟。这是确保您等待没有更多的一秒中有网络问题的事件。ping它自己每秒将发送一个ICMP数据包。本地主机可能不需要它,但是旧习惯很难解决。

You can use ping:

ping 127.0.0.1 -n 11 -w 1000 >nul: 2>nul:

It will wait 10 seconds.

The reason you have to use 11 is because the first ping goes out immediately, not after one second. The number should always be one more than the number of seconds you want to wait.

Keep in mind that the purpose of the -w is not to wait one second. It’s to ensure that you wait no more than one second in the event that there are network problems. ping on its own will send one ICMP packet per second. It’s probably not required for localhost, but old habits die hard.


回答 10

使用ping有更好的睡眠方式。您将要ping通一个不存在的地址,因此可以指定毫秒精度的超时。幸运的是,这样的地址是在标准(RFC 3330)中定义的,并且是192.0.2.x。这不是伪造的,它实际上是一个不存在的唯一目的的地址(可能不清楚,但即使在本地网络中也适用):

192.0.2.0/24-此块分配为“ TEST-NET”,用于文档和示例代码。它通常与供应商和协议文档中的域名example.com或example.net结合使用。此块内的地址不应出现在公共Internet上。

要睡眠123毫秒,请使用 ping 192.0.2.1 -n 1 -w 123 >nul

There is a better way to sleep using ping. You’ll want to ping an address that does not exist, so you can specify a timeout with millisecond precision. Luckily, such an address is defined in a standard (RFC 3330), and it is 192.0.2.x. This is not made-up, it really is an address with the sole purpose of not-existing. To be clear, this applies even in local networks.

192.0.2.0/24 – This block is assigned as “TEST-NET” for use in documentation and example code. It is often used in conjunction with domain names example.com or example.net in vendor and protocol documentation. Addresses within this block should not appear on the public Internet.

To sleep for 123 milliseconds, use ping 192.0.2.1 -n 1 -w 123 >nul

Update: As per the comments, there is also 127.255.255.255.


回答 11

如果您的系统上装有PowerShell,则只需执行以下命令:

powershell -command "Start-Sleep -s 1"

编辑:从我对类似主题的回答中,人们提出了一个问题,即启动Powershell所需的时间与您要等待的时间相比是很重要的。如果等待时间的准确性很重要(即不接受一两个秒的额外延迟),则可以使用以下方法:

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

这会花费执行Windows命令的时间,而powershell脚本会休眠直到该时间之后的5秒钟。因此,只要Powershell启动时间少于睡眠时间,这种方法就可以工作(在我的机器上大约为600ms)。

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

powershell -command "Start-Sleep -s 1"

Edit: from my answer on a similar thread, 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).


回答 12

timeout /t <seconds> <options>

例如,要使脚本执行不间断的2秒等待:

timeout /t 2 /nobreak >NUL

这意味着脚本将等待2秒再继续。

默认情况下,按键会中断超时,因此/nobreak如果您不希望用户能够中断(取消)等待,请使用开关。此外,超时将提供每秒的通知,以通知用户还需等待多长时间;这可以通过管道将命令被去除NUL

编辑:正如@martineau 在注释中指出的那样,该timeout命令仅在Windows 7及更高版本上可用。此外,该ping命令使用的处理器时间少于timeout。我仍然相信在timeout可能的地方使用它,因为它比ping“ hack” 更具可读性。在这里阅读更多。

timeout /t <seconds> <options>

For example, to make the script perform a non-uninterruptible 2-second wait:

timeout /t 2 /nobreak >NUL

Which means the script will wait 2 seconds before continuing.

By default, a keystroke will interrupt the timeout, so use the /nobreak switch if you don’t want the user to be able to interrupt (cancel) the wait. Furthermore, the timeout will provide per-second notifications to notify the user how long is left to wait; this can be removed by piping the command to NUL.

edit: As @martineau points out in the comments, the timeout command is only available on Windows 7 and above. Furthermore, the ping command uses less processor time than timeout. I still believe in using timeout where possible, though, as it is more readable than the ping ‘hack’. Read more here.


回答 13

只需将其放在您要等待的批处理文件中即可。

@ping 127.0.0.1 -n 11 -w 1000 > null

Just put this in your batch file where you want the wait.

@ping 127.0.0.1 -n 11 -w 1000 > null

回答 14

在记事本中,输入:

@echo off
set /a WAITTIME=%1+1
PING 127.0.0.1 -n %WAITTIME% > nul
goto:eof

现在,将另存为wait.bat保存在文件夹C:\ WINDOWS \ System32中,然后每当要等待时,请使用:

CALL WAIT.bat <whole number of seconds without quotes>

In Notepad, write:

@echo off
set /a WAITTIME=%1+1
PING 127.0.0.1 -n %WAITTIME% > nul
goto:eof

Now save as wait.bat in the folder C:\WINDOWS\System32, then whenever you want to wait, use:

CALL WAIT.bat <whole number of seconds without quotes>

回答 15

资源工具包,始终包含着这一点。至少从Windows 2000开始。

另外,Cygwin软件包sleep在路径中包含一个-plop,并包含cygwin.dll(或任何它所称的)名称和方法!

The Resource Kit has always included this. At least since Windows 2000.

Also, the Cygwin package has a sleep – plop that into your PATH and include the cygwin.dll (or whatever it’s called) and way to go!


回答 16

我喜欢阿卡尼的回应。我添加了它来处理日期,还使它能够处理厘秒%TIME%输出H:MM:SS.CC):

:delay
SET DELAYINPUT=%1
SET /A DAYS=DELAYINPUT/8640000
SET /A DELAYINPUT=DELAYINPUT-(DAYS*864000)

::Get ending centisecond (10 milliseconds)
FOR /F "tokens=1-4 delims=:." %%A IN ("%TIME%") DO SET /A H=%%A, M=1%%B%%100, S=1%%C%%100, X=1%%D%%100, ENDING=((H*60+M)*60+S)*100+X+DELAYINPUT
SET /A DAYS=DAYS+ENDING/8640000
SET /A ENDING=ENDING-(DAYS*864000)

::Wait for such a centisecond
:delay_wait
FOR /F "tokens=1-4 delims=:." %%A IN ("%TIME%") DO SET /A H=%%A, M=1%%B%%100, S=1%%C%%100, X=1%%D%%100, CURRENT=((H*60+M)*60+S)*100+X
IF DEFINED LASTCURRENT IF %CURRENT% LSS %LASTCURRENT% SET /A DAYS=DAYS-1
SET LASTCURRENT=%CURRENT%
IF %CURRENT% LSS %ENDING% GOTO delay_wait
IF %DAYS% GTR 0 GOTO delay_wait
GOTO :EOF

I like Aacini’s response. I added to it to handle the day and also enable it to handle centiseconds (%TIME% outputs H:MM:SS.CC):

:delay
SET DELAYINPUT=%1
SET /A DAYS=DELAYINPUT/8640000
SET /A DELAYINPUT=DELAYINPUT-(DAYS*864000)

::Get ending centisecond (10 milliseconds)
FOR /F "tokens=1-4 delims=:." %%A IN ("%TIME%") DO SET /A H=%%A, M=1%%B%%100, S=1%%C%%100, X=1%%D%%100, ENDING=((H*60+M)*60+S)*100+X+DELAYINPUT
SET /A DAYS=DAYS+ENDING/8640000
SET /A ENDING=ENDING-(DAYS*864000)

::Wait for such a centisecond
:delay_wait
FOR /F "tokens=1-4 delims=:." %%A IN ("%TIME%") DO SET /A H=%%A, M=1%%B%%100, S=1%%C%%100, X=1%%D%%100, CURRENT=((H*60+M)*60+S)*100+X
IF DEFINED LASTCURRENT IF %CURRENT% LSS %LASTCURRENT% SET /A DAYS=DAYS-1
SET LASTCURRENT=%CURRENT%
IF %CURRENT% LSS %ENDING% GOTO delay_wait
IF %DAYS% GTR 0 GOTO delay_wait
GOTO :EOF

回答 17

我一直在使用此C#睡眠程序。如果C#是您的首选语言,对您来说可能更方便:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace sleep
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length == 1)
            {
                double time = Double.Parse(args[0]);
                Thread.Sleep((int)(time*1000));
            }
            else
            {
                Console.WriteLine("Usage: sleep <seconds>\nExample: sleep 10");
            }
        }
    }
}

I have been using this C# sleep program. It might be more convenient for you if C# is your preferred language:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace sleep
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length == 1)
            {
                double time = Double.Parse(args[0]);
                Thread.Sleep((int)(time*1000));
            }
            else
            {
                Console.WriteLine("Usage: sleep <seconds>\nExample: sleep 10");
            }
        }
    }
}

回答 18

Perl一线式甚至比Python解决方案轻巧。

要睡眠七秒钟,请将其放在BAT脚本中:

perl -e "sleep 7"

该解决方案仅提供一秒钟的分辨率。

如果需要更高的分辨率,请使用CPAN中的Time :: HiRes模块。它提供了usleep()哪些睡眠时间(以微秒为单位)和nanosleep()哪些睡眠时间(以纳秒为单位)(两个函数都仅接受整数参数)。请参阅“堆栈溢出”问题。如何在Perl中睡眠一毫秒?有关更多详细信息。

我已经使用ActivePerl多年了。这很容易安装。

Even more lightweight than the Python solution is a Perl one-liner.

To sleep for seven seconds put this in the BAT script:

perl -e "sleep 7"

This solution only provides a resolution of one second.

If you need higher resolution then use the Time::HiRes module from CPAN. It provides usleep() which sleeps in microseconds and nanosleep() which sleeps in nanoseconds (both functions takes only integer arguments). See the Stack Overflow question How do I sleep for a millisecond in Perl? for further details.

I have used ActivePerl for many years. It is very easy to install.


回答 19

或以命令行Python为例,例如6秒半:

python -c "import time;time.sleep(6.5)"

Or command line Python, for example, for 6 and a half seconds:

python -c "import time;time.sleep(6.5)"

回答 20

ping的用法很好,只要您只想“稍等”即可。这是因为您依赖于下面的其他功能,例如您的网络正常工作以及127.0.0.1上没有任何应答的事实。;-)也许它不太可能失败,但并非不可能…

如果要确保正好在指定的时间等待,则应使用该sleep功能(该功能还具有不使用CPU电源或等待网络就绪的优势)。

查找已经制作好的可执行文件以进行睡眠是最方便的方法。只需将其放入Windows文件夹或标准路径的任何其他部分,它便始终可用。

否则,如果您具有编译环境,则可以轻松地自己制作一个。该Sleep功能在中可用kernel32.dll,因此您只需要使用该功能即可。:-)对于VB / VBA,请在源代码的开头声明以下内容以声明睡眠功能:

private Declare Sub Sleep Lib "kernel32" Alias "Sleep" (byval dwMilliseconds as Long)

对于C#:

[DllImport("kernel32.dll")]
static extern void Sleep(uint dwMilliseconds);

您可以在睡眠功能(MSDN)中找到有关此功能(从Windows 2000开始可用)的更多信息。

在标准C中,sleep()包含在标准库中,并且在Microsoft的Visual Studio C中,该函数名为Sleep(),如果内存为我服务。;-)这两个参数以秒为单位,而不是前两个声明以毫秒为单位。

The usage of ping is good, as long as you just want to “wait for a bit”. This since you are dependent on other functions underneath, like your network working and the fact that there is nothing answering on 127.0.0.1. ;-) Maybe it is not very likely it fails, but it is not impossible…

If you want to be sure that you are waiting exactly the specified time, you should use the sleep functionality (which also have the advantage that it doesn’t use CPU power or wait for a network to become ready).

To find an already made executable for sleep is the most convenient way. Just drop it into your Windows folder or any other part of your standard path and it is always available.

Otherwise, if you have a compiling environment you can easily make one yourself. The Sleep function is available in kernel32.dll, so you just need to use that one. :-) For VB / VBA declare the following in the beginning of your source to declare a sleep function:

private Declare Sub Sleep Lib "kernel32" Alias "Sleep" (byval dwMilliseconds as Long)

For C#:

[DllImport("kernel32.dll")]
static extern void Sleep(uint dwMilliseconds);

You’ll find here more about this functionality (available since Windows 2000) in Sleep function (MSDN).

In standard C, sleep() is included in the standard library and in Microsoft’s Visual Studio C the function is named Sleep(), if memory serves me. ;-) Those two takes the argument in seconds, not in milliseconds as the two previous declarations.


回答 21

适用于Windows 2000之后的所有Windows版本的最佳解决方案是:

timeout numbersofseconds /nobreak > nul

The best solution that should work on all Windows versions after Windows 2000 would be:

timeout numbersofseconds /nobreak > nul

回答 22

pathping.exe可以睡少于一秒钟。

@echo off
setlocal EnableDelayedExpansion 
echo !TIME! & pathping localhost -n -q 1 -p %~1 2>&1 > nul & echo !TIME!

> sleep 10
17:01:33,57
17:01:33,60

> sleep 20
17:03:56,54
17:03:56,58

> sleep 50
17:04:30,80
17:04:30,87

> sleep 100
17:07:06,12
17:07:06,25

> sleep 200
17:07:08,42
17:07:08,64

> sleep 500
17:07:11,05
17:07:11,57

> sleep 800
17:07:18,98
17:07:19,81

> sleep 1000
17:07:22,61
17:07:23,62

> sleep 1500
17:07:27,55
17:07:29,06

The pathping.exe can sleep less than second.

@echo off
setlocal EnableDelayedExpansion 
echo !TIME! & pathping localhost -n -q 1 -p %~1 2>&1 > nul & echo !TIME!

.

> sleep 10
17:01:33,57
17:01:33,60

> sleep 20
17:03:56,54
17:03:56,58

> sleep 50
17:04:30,80
17:04:30,87

> sleep 100
17:07:06,12
17:07:06,25

> sleep 200
17:07:08,42
17:07:08,64

> sleep 500
17:07:11,05
17:07:11,57

> sleep 800
17:07:18,98
17:07:19,81

> sleep 1000
17:07:22,61
17:07:23,62

> sleep 1500
17:07:27,55
17:07:29,06

回答 23

我对此印象深刻:

http://www.computerhope.com/batch.htm#02

choice /n /c y /d y /t 5 > NUL

从技术上讲,您是在告诉choice命令仅接受y。它的默认值为y,在5秒钟内这样做,不绘制提示,并将它说的任何内容转储给NUL(例如Linux上的null终端)。

I am impressed with this one:

http://www.computerhope.com/batch.htm#02

choice /n /c y /d y /t 5 > NUL

Technically, you’re telling the choice command to accept only y. It defaults to y, to do so in 5 seconds, to draw no prompt, and to dump anything it does say to NUL (like null terminal on Linux).


回答 24

您还可以使用.vbs文件执行特定的超时:

下面的代码创建.vbs文件。将其放在您的rbatch代码顶部附近:

echo WScript.sleep WScript.Arguments(0) >"%cd%\sleeper.vbs"

然后,下面的代码打开.vbs并指定等待时间:

start /WAIT "" "%cd%\sleeper.vbs" "1000"

在上面的代码中,“ 1000”是要发送到.vbs文件的时间延迟值,以毫秒为单位,例如1000 ms = 1 s。您可以将这部分更改为任意长。

完成后,下面的代码将删除.vbs文件。将其放在批处理文件的末尾:

del /f /q "%cd%\sleeper.vbs"

这是所有代码,因此很容易复制:

echo WScript.sleep WScript.Arguments(0) >"%cd%\sleeper.vbs"
start /WAIT "" "%cd%\sleeper.vbs" "1000"
del /f /q "%cd%\sleeper.vbs"

You can also use a .vbs file to do specific timeouts:

The code below creates the .vbs file. Put this near the top of you rbatch code:

echo WScript.sleep WScript.Arguments(0) >"%cd%\sleeper.vbs"

The code below then opens the .vbs and specifies how long to wait for:

start /WAIT "" "%cd%\sleeper.vbs" "1000"

In the above code, the “1000” is the value of time delay to be sent to the .vbs file in milliseconds, for example, 1000 ms = 1 s. You can alter this part to be however long you want.

The code below deletes the .vbs file after you are done with it. Put this at the end of your batch file:

del /f /q "%cd%\sleeper.vbs"

And here is the code all together so it’s easy to copy:

echo WScript.sleep WScript.Arguments(0) >"%cd%\sleeper.vbs"
start /WAIT "" "%cd%\sleeper.vbs" "1000"
del /f /q "%cd%\sleeper.vbs"

回答 25

在Windows Vista上,您具有TIMEOUTSLEEP命令,但是要在Windows XP或Windows Server 2003上使用它们,则需要Windows Server 2003资源工具包

在这里,您可以很好地了解其他睡眠方式(ping方法是最受欢迎的方法,因为它可以在每台Windows机器上使用),但是(至少)没有提到(至少)一种使用W32TM(时间服务)命令的睡眠方法:

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

在此处应将N替换为要暂停的秒数。此外,它无需任何先决条件即可在每个Windows系统上运行。

也可以使用Typeperf:

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

使用mshta和javascript(可在一秒钟内用于睡眠):

start "" /wait /min /realtime mshta "javascript:setTimeout(function(){close();},5000)"

这应该更加精确(等待一秒钟)-自编译可执行文件依赖于.net

@if (@X)==(@Y) @end /* JScript comment
@echo off
setlocal
::del %~n0.exe /q /f
::
:: For precision better call this like
:: call waitMS 500
:: in order to skip compilation in case there's already built .exe
:: as without pointed extension first the .exe will be called due to the ordering in PATEXT variable
::
::
for /f "tokens=* delims=" %%v in ('dir /b /s /a:-d  /o:-n "%SystemRoot%\Microsoft.NET\Framework\*jsc.exe"') do (
   set "jsc=%%v"
)

if not exist "%~n0.exe" (
    "%jsc%" /nologo /w:0 /out:"%~n0.exe" "%~dpsfnx0"
)


%~n0.exe %*

endlocal & exit /b %errorlevel%


*/


import System;
import System.Threading;

var arguments:String[] = Environment.GetCommandLineArgs();
function printHelp(){
    Console.WriteLine(arguments[0]+" N");
    Console.WriteLine(" N - milliseconds to wait");
    Environment.Exit(0);    
}

if(arguments.length<2){
    printHelp();
}

try{
    var wait:Int32=Int32.Parse(arguments[1]);
    System.Threading.Thread.Sleep(wait);
}catch(err){
    Console.WriteLine('Invalid Number passed');
    Environment.Exit(1);
}

From Windows Vista on you have the TIMEOUT and SLEEP commands, but to use them on Windows XP or Windows Server 2003, you’ll need the Windows Server 2003 resource tool kit.

Here you have a good overview of sleep alternatives (the ping approach is the most popular as it will work on every Windows machine), but there’s (at least) one not mentioned which (ab)uses the W32TM (Time Service) command:

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

Where you should replace the N with the seconds you want to pause. Also, it will work on every Windows system without prerequisites.

Typeperf can also be used:

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

With mshta and javascript (can be used for sleep under a second):

start "" /wait /min /realtime mshta "javascript:setTimeout(function(){close();},5000)"

This should be even more precise (for waiting under a second) – self compiling executable relying on .net:

@if (@X)==(@Y) @end /* JScript comment
@echo off
setlocal
::del %~n0.exe /q /f
::
:: For precision better call this like
:: call waitMS 500
:: in order to skip compilation in case there's already built .exe
:: as without pointed extension first the .exe will be called due to the ordering in PATEXT variable
::
::
for /f "tokens=* delims=" %%v in ('dir /b /s /a:-d  /o:-n "%SystemRoot%\Microsoft.NET\Framework\*jsc.exe"') do (
   set "jsc=%%v"
)

if not exist "%~n0.exe" (
    "%jsc%" /nologo /w:0 /out:"%~n0.exe" "%~dpsfnx0"
)


%~n0.exe %*

endlocal & exit /b %errorlevel%


*/


import System;
import System.Threading;

var arguments:String[] = Environment.GetCommandLineArgs();
function printHelp(){
    Console.WriteLine(arguments[0]+" N");
    Console.WriteLine(" N - milliseconds to wait");
    Environment.Exit(0);    
}

if(arguments.length<2){
    printHelp();
}

try{
    var wait:Int32=Int32.Parse(arguments[1]);
    System.Threading.Thread.Sleep(wait);
}catch(err){
    Console.WriteLine('Invalid Number passed');
    Environment.Exit(1);
}

回答 26

有多种方法可以在cmd / batch中完成“ sleep ”:

我最喜欢的一个:

TIMEOUT /NOBREAK 5 >NUL 2>NUL

这将使控制台停止5秒钟,没有任何输出。

最常被使用:

ping localhost -n 5 >NUL 2>NUL

这将尝试建立localhost5次连接。由于它是托管在您的计算机上的,因此它将始终可以访问该主机,因此,它每秒将尝试新的主机。该-n标志指示脚本将尝试连接多少次。在这种情况下为5,因此它将持续5秒。

最后一个的变体:

ping 1.1.1.1 -n 5 >nul

在此脚本中,与最后一个脚本进行比较存在一些差异。这不会尝试调用localhost。相反,它将尝试连接到1.1.1.1一个非常快速的网站。仅当您具有活动的Internet连接时,此操作才会持续5秒钟否则,它将持续约15分钟才能完成操作。我不建议使用此方法。

ping 127.0.0.1 -n 5 >nul

这与示例2(使用最多)完全相同。另外,您还可以使用:

ping [::1] -n 5 >nul

而是使用IPv6的localhost版本。

有很多方法可以执行此操作。但是,对于Windows Vista和更高版本,我更喜欢方法1,对于较早版本的OS,我更喜欢最常用的方法(方法2)。

There are lots of ways to accomplish a ‘sleep‘ in cmd/batch:

My favourite one:

TIMEOUT /NOBREAK 5 >NUL 2>NUL

This will stop the console for 5 seconds, without any output.

Most used:

ping localhost -n 5 >NUL 2>NUL

This will try to make a connection to localhost 5 times. Since it is hosted on your computer, it will always reach the host, so every second it will try the new every second. The -n flag indicates how many times the script will try the connection. In this case is 5, so it will last 5 seconds.

Variants of the last one:

ping 1.1.1.1 -n 5 >nul

In this script there are some differences comparing it with the last one. This will not try to call localhost. Instead, it will try to connect to 1.1.1.1, a very fast website. The action will last 5 seconds only if you have an active internet connection. Else it will last approximately 15 to complete the action. I do not recommend using this method.

ping 127.0.0.1 -n 5 >nul

This is exactly the same as example 2 (most used). Also, you can also use:

ping [::1] -n 5 >nul

This instead, uses IPv6’s localhost version.

There are lots of methods to perform this action. However, I prefer method 1 for Windows Vista and later versions and the most used method (method 2) for earlier versions of the OS.


回答 27

您可以通过将PAUSE消息放在标题栏中来实现幻想:

@ECHO off
SET TITLETEXT=Sleep
TITLE %TITLETEXT%
CALL :sleep 5
GOTO :END
:: Function Section
:sleep ARG
ECHO Pausing...
FOR /l %%a in (%~1,-1,1) DO (TITLE Script %TITLETEXT% -- time left^
 %%as&PING.exe -n 2 -w 1000 127.1>NUL)
EXIT /B 0
:: End of script
:END
pause
::this is EOF

You can get fancy by putting the PAUSE message in the title bar:

@ECHO off
SET TITLETEXT=Sleep
TITLE %TITLETEXT%
CALL :sleep 5
GOTO :END
:: Function Section
:sleep ARG
ECHO Pausing...
FOR /l %%a in (%~1,-1,1) DO (TITLE Script %TITLETEXT% -- time left^
 %%as&PING.exe -n 2 -w 1000 127.1>NUL)
EXIT /B 0
:: End of script
:END
pause
::this is EOF

回答 28

这已在Windows XP SP3和Windows 7上进行了测试,并使用CScript。我采取了一些安全措施,以免出现del“”提示。(/q很危险)

等待一秒钟:

sleepOrDelayExecution 1000

等待500毫秒,然后在执行以下操作:

sleepOrDelayExecution 500 dir \ /s

sleepOrDelayExecution.bat:

@echo off
if "%1" == "" goto end
if NOT %1 GTR 0 goto end
setlocal
set sleepfn="%temp%\sleep%random%.vbs"
echo WScript.Sleep(%1) >%sleepfn%
if NOT %sleepfn% == "" if NOT EXIST %sleepfn% goto end
cscript %sleepfn% >nul
if NOT %sleepfn% == "" if EXIST %sleepfn% del %sleepfn%
for /f "usebackq tokens=1*" %%i in (`echo %*`) DO @ set params=%%j
%params%
:end

This was tested on Windows XP SP3 and Windows 7 and uses CScript. I put in some safe guards to avoid del “” prompting. (/q would be dangerous)

Wait one second:

sleepOrDelayExecution 1000

Wait 500 ms and then run stuff after:

sleepOrDelayExecution 500 dir \ /s

sleepOrDelayExecution.bat:

@echo off
if "%1" == "" goto end
if NOT %1 GTR 0 goto end
setlocal
set sleepfn="%temp%\sleep%random%.vbs"
echo WScript.Sleep(%1) >%sleepfn%
if NOT %sleepfn% == "" if NOT EXIST %sleepfn% goto end
cscript %sleepfn% >nul
if NOT %sleepfn% == "" if EXIST %sleepfn% del %sleepfn%
for /f "usebackq tokens=1*" %%i in (`echo %*`) DO @ set params=%%j
%params%
:end

回答 29

由于其他人建议使用第三方程序(Python,Perl,自定义应用程序等),因此,另一个可供选择的选择是Windows的GNU CoreUtils,网址http://gnuwin32.sourceforge.net/packages/coreutils.htm

2个部署选项:

  1. 安装完整的软件包(将包括完整的CoreUtils,依赖项,文档等)。
  2. 仅安装“ sleep.exe”二进制文件和必要的依赖项(使用depends.exe获取依赖项)。

部署CoreUtils的一个好处是,您还将获得许多其他有助于编写脚本的程序(Windows批处理还有很多不足之处)。

Since others are suggesting 3rd party programs (Python, Perl, custom app, etc), another option is GNU CoreUtils for Windows available at http://gnuwin32.sourceforge.net/packages/coreutils.htm.

2 options for deployment:

  1. Install full package (which will include the full suite of CoreUtils, dependencies, documentation, etc).
  2. Install only the ‘sleep.exe’ binary and necessary dependencies (use depends.exe to get dependencies).

One benefit of deploying CoreUtils is that you’ll additionally get a host of other programs that are helpful for scripting (Windows batch leaves a lot to be desired).