Как сделать задержку в bat файле
Перейти к содержимому

Как сделать задержку в bat файле

  • автор:

Жизнь без алкоголя запойного алкоголика | Родная душа – статьи, компьютер, Интернет | Создание, оптимизация сайтов, блогов | HTML, CSS, ява-скрипт.

Записки алкоголика.
(Прикладное бумаготворчество.
Литературный алкогольный стеб)

Задержка времени (пауза, тайм-аут) в бат-файле

Вот, нашёл в Сети рабочий пример для устройства задержки времени
(пауза, тайм-аут) при выполнении команды в bat-файле:

echo wscript.Sleep 30000>»%temp%\sleep30.vbs»
cscript //nologo «%temp%\sleep30.vbs»
del «%temp%\sleep30.vbs»

Работает в любой ОС Windows, аж бегом

Зачем нужна задержка (пауза, тайм-аут) при выполнении команды в bat-файле?

У всех – по-разному.
Лично мне она (пауза) понадобилась вот для чего:

– Взял простенький bat-файл для очистки временных папок и бросил его в АВТОЗАГРУЗКУ
Прикололся, типа – чтобы этот батничек чистил временные каталоги при запуске системы.
Текст батника вытащил из стандартного Total Commander-a:

cmd /c title Очистка временной папки &cd/d %temp%&rd/s/q %temp% 2>nul &cd/d %tmp%&rd/s/q %tmp% 2>nul &cd/d C:\Windows\Prefetch &del *.pf 2>nul &cd/d C:\Windows\Temp&rd/s/q c:\windows\temp 2>nul

Всё-бы ничего, да только такая процедура очистки временных папок при загрузке –
сносит полезные файлы и система выдаёт окно ошибки

Досадно.
Однако, устройство паузы в 30 сек. решило всю проблему.
И система грузится, и папки темпов — чистятся.

Полный текст bat-файла стал теперь таким:

echo wscript.Sleep 30000>»%temp%\sleep30.vbs»
cscript //nologo «%temp%\sleep30.vbs»
del «%temp%\sleep30.vbs»
cmd /c title Очистка временной папки &cd/d %temp%&rd/s/q %temp% 2>nul &cd/d %tmp%&rd/s/q %tmp% 2>nul &cd/d C:\Windows\Prefetch &del *.pf 2>nul &cd/d C:\Windows\Temp&rd/s/q c:\windows\temp 2>nul

Прим. Лошади понятно, что изменив цифру 30 на своё значение,
можно получить другие величины паузы в секундах в bat-файле.

Начиная с VISTA, в операционных системах семейства Windows присутствует команда TIMEOUT. Эта команда принимает значение таймаута, равного фиксированному периоду времени ожидания (в секундах) до выполнения команды или ожидание до нажатия клавиши. Имеется также параметр, зaдающий игнорирование нажатий клавиш.

Синтаксис
TIMEOUT [/T] 50 [/NOBREAK]

Параметры

/T 50 Таймаут = 50 сек. Время ожидания в секундах. Допустимый интервал: от -1 до 99999 секунд. Значение, равное -1 задает неограниченное время ожидания до нажатия клавиши. /NOBREAK Игнорировать нажатия клавиш, ждать указанное время. /? Отображение справки в командной строке.

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

Весь текст примера можно внести в bat-файл,
запустить и посмотреть, как это работает.
Впечатляет.

Как сделать задержку в bat файле

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

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.
The 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 IF ERRORLEVEL 255 ECHO Invalid parameter ends with an «invisible» BELL character, which is ASCII character 7 (beep) or ^G (Ctrl+G).

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):

SystemTrayMessage screenshot

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:

Как сделать задержку в командном файле

wikiHow работает по принципу вики, а это значит, что многие наши статьи написаны несколькими авторами. При создании этой статьи над ее редактированием и улучшением работали, в том числе анонимно, 10 человек(а).

Количество просмотров этой статьи: 44 545.

Из этой статьи вы узнаете, как предотвратить немедленный запуск пакетного файла, когда его открывают. Есть несколько различных команд, которые можно использовать для задержки пакетного файла. Имейте в виду, что вы должны хорошо знать, как создавать пакетные файлы, прежде чем пытаться сделать его задержку.

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?

Massimo's user avatar

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 :

Massimo's user avatar

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

Wasif's user avatar

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.

Wasif's user avatar

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).

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *