How to wait in a batch script? [duplicate]
I am trying to write a batch script and trying to wait 10 seconds between 2 function calls. The command:
Does not make the batch file wait for 10 seconds.
I am running Windows XP.
Note: This is not a complete duplicate of Sleeping in a batch file as the other question is about also about python, while this is about windows batch files.
6 Answers 6
You can ping an address that doesn’t exist and specify the desired timeout:
And since the address does not exist, it’ll wait 10,000 ms (10 seconds) and return.
- The -w 10000 part specifies the desired timeout in milliseconds.
- The -n 1 part tells ping that it should only try 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 using the above technique:
NOTE (September 2020): The 192.0.2.x address is reserved as per RFC 3330 so it definitely will not exist in the real world. Quoting from the spec:
How to sleep in a batch file?
How to pause execution for a while in a Windows batch file between a command and the next one?
5 Answers 5
The correct way to sleep in a batch file is to use the timeout command, introduced in Windows 2000.
The timeout would get interrupted if the user hits any key; however, the command also accepts the optional switch /nobreak , which effectively ignores anything the user may press, except an explicit CTRL-C :
Additionally, if you don’t want the command to print its countdown on the screen, you can redirect its output to NUL :
Since it applies here, too, I’ll copy my answer from another site.
If you want to use ping, there is a better way. 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 (it may not be clear, but it 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
You can sleep in Batch using powershell:
Milliseconds
Seconds
You can also insert a ping to localhost. This will take 4 seconds to complete (by default). It is considered a kludge by some, but works quite well all the same.
Disclaimer: this is not the «ideal» solution, so don’t bother beating me over the head with that like done to those recommending ping .
When possible, use timeout for sure. But as noted in the comments, that’s not always an option (e.g. in non-interactive mode). After that, I agree that the ping «kludge» is perhaps the next best option, as it is very simple. That said, I offer another option. embed some VB Script.
The basis of this solution has all sorts of application beyond this. Often VBS can do things that batch cannot, or at the very least do so with drastically more ease. Using the technique illustrated here, you can mix the two (not «seamlessly», but «functionally». ).
Here’s a one liner, to create a temp script, execute it, then delete it. The script does the sleeping for you (for 3 seconds in this example).
Сделать задержку в командном файле
Статья описывает шесть способов организации командном файле BAT/CMD задержки, задаваемой в секундах.
Хотя чаще bat файлы выполняются полностью автоматически, в некоторых случаях может понадобиться
- Приостановка выполнения bat файла перед повтором неудачной операции, например, подключения к сетевому диску по WebDav
- Пауза в несколько секунд после выполнения команды, чтобы пользователь мог просмотреть результат выполнения
- Интервал между командами, каким-то образом влияющими друг на друга
Варианты задержки в bat файле
Программа PING
Запускаю PING с нужным числом запросов (примерно 1 секунда на запрос), например, на 30 секунд:
Никакой информации при этом не выводится, так как вывод перенаправлен в nul ..
Преимущества: работает на всех Windows компьютеров , т.к. программа PING установлена всегда и на всех версиях.
Недостатки: время задержки кратно секунде, т.е. нельзя сделать задержку менее 1 секунды, например, в 200 или 500 мс.
Программа SLEEP.EXE из Windows Resource Kit
Консольное приложение sleep.exe входит в пакет программ Windows XP Resource Kit (или Windows 2003 Resource Kit. Из краткой справки
Поэтому для задержки в 10 секунд надо запустить
а для задержки 500 мс надо написать
Преимущества: можно задавать задержки не только в секундах, но и в миллисекундах. Хотя необходимости в коротких задержках менее секунды у меня ни разу не возникало. Если у вас есть примеры такой задачи, напишите, пожалуйста, в комментариях.
Недостатки: SLEEP.EXE не входит в стандартный комплект Windows и может оказаться, что на целевом компьютере этого файла нет, и его надо будет распространять вместе с bat файлом.
Скрипт WSH/JScript
Создаём на JScript небольшой скрипт SLEEP.JS, использующий функцию WScript.Sleep:
и вызываем его из командного файла, например, задержка 10 секунд:
Аналогичный скрипт можно написать на VBScript.
Преимущества: можно задавать задержки в секундах и миллисекундах; не требуются сторонние программы.
Недостатки: требуется распространять файл скрипта вместе с bat файлом или вставлять в bat файл код для создания файла скрипта, например, так:
Программа timeout.exe
Консольное приложение timeout.exe предустановлена в современных версиях Windows и выполняет задержку в секундах с возможностью выхода из ожидания по нажатию клавиши:
Если пауза не должна прерываться по нажатию клавиши, то надо добавить параметр /nobreak:
Время можно задавать только в секундах.
Плюсы программы — отображение информации для пользователя, чтобы он понимал, что происходит сейчас в bat файле, возможность продолжения работы bat файла как по времени, так и по клавише.
Скрипт PowerShell
Функция Start-Sleep приостанавливает действие в скрипте или сеансе на указанное время, например, задержка 10 секунд:
Программа nhmb
Программа nhmb имеет встроенный таймер и используется в bat файлах для создания задержки:
Программ nhmb выводит окно сообщения MessageBox с таймером в заголовке, чтобы пользователь мог понять, что сейчас идёт задержка перед следующей операцией и мог повлиять на ход выполнения:
Какой вариант выбрать?
В итоге, вариантов много, а что применять? На этой картинке показано тестирование всех вариантов:
Ответ зависит от задачи:
- Если требуется просто остановить выполнение bat файла на несколько секунд без вывода информации пользователю и без ожидания действий с его стороны, то наилучший вариант – старый добрый способ на основе ping, потому что работает везде, прост в использовании и не требует дополнительных файлов.
- Если требуется сделать задержку с выводом информации в окне командной строки, то лучше подходит timeout.exe – показывает оставшееся время, работает в современных версиях Windows и не требует дополнительных файлов.
- Если пауза нужна с выводом информации пользователю в диалоговом окне Message Box, то nhmb.exe открывает всплывающее окно с таймером в заголовке.
Узнать больше
Файлы для скачивания
Скачать bat файлы, скрипты и исполняемые файлы, описанные в этой статье (программы nhts и nhcolor не требуются для паузы и были добавлены для оформления вывода bat файла)
Программы
nhmb — показ всплывающего окна MessageBox с таймером обратного отсчёта
Как в батнике сделать задержку
To make a batch file wait for a number of seconds there are several options available:
PAUSE
The most obvious way to pause a batch file is of course the PAUSE command. This will stop execution of the batch file until someone presses «any key». Well, almost any key: Ctrl, Shift, NumLock etc. won’t work.
This is fine for interactive use, but sometimes we just want to delay the batch file for a fixed number of seconds, without user interaction.
SLEEP
SLEEP was included in some of the Windows Resource Kits.
It waits for the specified number of seconds and then exits.
will delay execution of the next command by 10 seconds.
There are lots of SLEEP clones available, including the ones mentioned in the UNIX Ports paragraph at the end of this page.
TIMEOUT
TIMEOUT was included in some of the Windows Resource Kits, but is a standard command as of Windows 7.
It waits for the specified number of seconds or a keypress, and then exits.
So, unlike SLEEP , TIMEOUT ‘s delay can be «bypassed» by pressing a key.
will delay execution of the next command by 10 seconds, or until a key is pressed, whichever is shorter.
You may not always want to abort the delay with a simple key press, in which case you can use TIMEOUT ‘s optional /NOBREAK switch:
You can still abort the delay, but this requires Ctrl+C instead of just any key, and will raise an ErrorLevel 1.
For any MS-DOS or Windows version with a TCP/IP client, PING can be used to delay execution for a number of seconds.
will delay execution of the next command for (a little over) 5 seconds seconds (default interval between pings is 1 second, the last ping will add only a minimal number of milliseconds to the delay).
So always specify the number of seconds + 1 for the delay.
The PING time-out technique is demonstrated in the following examples:
PMSleep.bat for Windows NT
PMSlpW9x.bat for Windows 95/98
NETSH
NETSH may seem an unlikely choice to generate delays, but it is actually much like using PING :
will ping localhost, which takes about 5 seconds — hence a 5 seconds delay.
NETSH is native in Windows XP Professional and later versions.
Unfortunately however, this trick will only work in Windows XP/Server 2003.
CHOICE
In MS-DOS 6, Windows 9*/ME and NT 4
will add a 10 seconds delay.
By using REM | before the CHOICE command, the standard input to CHOICE is blocked, so the only «way out» for CHOICE is the time-out specified by the /T parameter.
This idea was borrowed from Laurence Soucy, I added the /C parameter to make it language independent (the simpler REM | CHOICE /T:N,10 >NUL will work in many but not all languages).
The CHOICE delay technique is demonstrated in the following example, Wait.bat:
Note: | The line ECHO Invalid parameter ends with an «invisible» BELL character, which is ASCII character 7 (beep) or ^G (Ctrl+G). |
In Windows 10 the REM trick no longer works, and the default option is no longer specified with the /T switch, but with a separate /D switch:
This means that, unlike in DOS, in Windows 10 you can skip the delay by pressing one of the choices specified with the /C switch.
The CHOICE delay technique is demonstrated in the following example, Wait.cmd:
CountDown
For longer delay times especially, it would be nice to let the user know what time is left.
That is why I wrote CountDown.exe (in C#): it will count down showing the number of seconds left.
Pressing any key will skip the remainder of the count down, allowing the batch file to continue with the next command.
You may append the counter output to a custom text, like this ( @ECHO OFF required):
SystemTrayMessage
SystemTrayMessage.exe is a program I wrote to display a tooltip message in the system tray’s notification area.
By default it starts displaying a tooltip which will be visible for 10 seconds (or any timeout specified), but the program will terminate immediately after starting the tooltip. The icon will remain in the notification area after the timeout elapsed, until the mouse pointer hovers over it.
By using its optional /W switch, the program will wait for the timeout to elapse and then hide the icon before terminating.
Display a tooltip message for 60 seconds while continuing immediately:
Display a tooltip message and wait for 60 seconds:
Or more sophisticated (requires CountDown.exe too):
Non-DOS Scripting
In PowerShell you can use Start-Sleep when you need a time delay.
The delay can be specified either in seconds (default) or in milliseconds.
The following batch code uses PowerShell to generate a delay:
Or if you want to allow fractions of seconds:
Note that starting PowerShell.exe in a batch file may add an extra second to the specified delay.
Use the SysSleep function whenever you need a time delay in Rexx scripts.
SysSleep is available in OS/2’s (native) RexxUtil module and in Patrick McPhee’s RegUtil module for 32-bits Windows.
Use the Sleep command for time delays in KiXtart scripts.
Use WScript.Sleep, followed by the delay in milliseconds in VBScript and JScript (unfortunately, this method is not available in HTAs).
The following batch code uses a temporary VBScript file to generate an accurate delay:
Or if you want to allow the user to skip the delay:
UNIX Ports
Compiled versions of SLEEP are also available in these Unix ports: