Windows 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-файл,
запустить и посмотреть, как это работает.
Впечатляет.

Windows bat файлы пауза

Рассмотрим основные варианты организации ожидания ( паузы ) в bat / cmd файлах.

Для решения этой задачи в операционных системах, начиная с VISTA, присутствует команда timeout. Так, для ожидания 10 секунд следует выполнить команду.

Если не использовать параметр /NOBREAK, то ожидание может быть прервано нажатием любой клавиши.

Поскольку эта задача вставала перед разработчиками задолго до появления этой утилиты, те, у которых операционная система младше, могут воспользоваться накопившемся опытом.
Для организации паузы есть специальная утилита, входящая в состав Resource Kit (Ресурскита).
Пакеты Microsoft Windows Deployment Kit и Windows Resource Kit бесплатно распространяется microsoft.com. Этот пакет содержит ряд полезных и. как бы так сказать. других утилит.

Читайте также:  Отключение зпс астра линукс

Если вы уже устали бродить по бескрайним просторам сайта microsoft.com, постоянно возвращаясь на одни и те же страницы, то можете скачать эту утилиту здесь

Как и во многих других случаях, может помочь утилита nircmd.
(На момент написания страницы описание возможностей утилиты было здесь. C этим списком я рекомендую ознакомится, даже если для текущей задачи будет использовано другое решение.)

На просторах интернета можно найти утилиту wait.exe. Точнее, даже несколько разных, включая исходные тексты программы. Поэтому я не привожу здесь параметров вызова, смотрите их описание.

Для организации паузы можно использовать утилиты, ожидающих определенное событие заданное время.
При условии, что событие не наступит, получается ожидание требуемого интервала времени.
Так, паузу можно создать при помощи команды ping:

-n 1 — выполнить один запрос
-w 100000 — ждать ответа 100 секунд
(значение указывается в миллисекундах)
10.10.254.254 — IP адрес, который заведомо не существует в локальной сети (важно!), следовательно, никогда не ответит на ping т. е. событие не наступит.
>nul — перенаправление всего вывода команды ping в никуда.

Еще одно решение — посылать пинг на заведомо существующий адрес — т. е. самому себе. Количество посылаемых пакетов должно быть на единицу больше количества ожидаемых секунд. Так, для ожидания 5 секунд следует выполнить команду:

В том же пакете Ресурскит есть утилита choice, которую при известной доле извращенности можно использовать для тех же целей:

Для любителей экзотики.
Можно вычислить время окончания интервала ожидания и занять чем-то несчастный процессор до наступления этого события. Как результат — пауза организована только средствами bat / cmd.
Привожу слегка исправленный пример, взятый с сайта http://www.oszone.net.

0,-3% :: пауза на 15 секунд call :sleep 15 :: Другие действия echo Сейчас %time:

0,-3% pause goto :EOF :sleep echo Пауза на %1 секунд. set /a ftime=100%time:

6,-3%%%100+%1 if %ftime% GEQ 60 set /a ftime-=60 :loop set ctime=%time:

6,-3% if /i %ftime% NEQ %ctime% goto :loop exit /b 0

Данная процедура позволит организовать задержку в выполнении. Время ожидания должно быть меньше 60 сек.

Для вопросов, обсуждений, замечаний, предложений и т. п. можете использовать раздел форума этого сайта (требуется регистрация).

Новый раздел о средствах командной строки в рамках этого же проекта расположен здесь

Windows bat файлы пауза

  • Home
  • News
  • FAQ
  • Search
  • Scripting Languages
    • Batch Files
      • Getting Started
      • Batch Techniques
      • Batch HowTos
      • Commands
      • Command Line Switches
      • Shutdown Commands
      • Short Command Line Tips
      • Admin One-Liners
      • Examples
      • Samples Collections
      • Tools
      • Links
      • Books
      • Challenges
    • C#
      • Getting Started
      • C# Code Snippets
      • Examples
      • Development Software
        • Visual Studio
        • Visual Studio Community Edition
        • Visual Studio Code
      • Books
    • KiXtart
      • Getting Started
      • Examples
      • Links
      • Tools
      • Books
    • Perl
      • Getting Started
      • Examples
      • Links
      • Tools
    • PowerShell
      • Getting Started
      • PowerShell Code Snippets
      • Examples
      • Links
      • Tools
    • Regular Expressions
      • Getting Started
      • Expressions
      • Examples
      • Links
      • Tools
      • Books
    • Rexx
      • Getting Started
      • Examples
      • OS/2 LAN Server
      • Links
      • Tools
      • Books
    • VBScript & WSH
      • Getting Started
      • VBScript Techniques
      • Examples
      • HTA & WSC Examples
      • Links
      • Tools
      • Books
      • Challenges
  • Technologies
    • WMI
      • Getting Started
      • Examples
      • WMI Queries for Hardware
      • Links
      • Tools
      • Books
    • ADSI
      • Getting Started
      • Examples
      • Links
      • Tools
      • Books
    • Silent Installs
      • General
      • Windows Installer
      • Specific Software
      • Software Requirements
      • Hardware Requirements
  • Books
  • Scripting Tools
    • Batch Utilities
    • Compilers
    • Editors
    • Code Generators
    • Regular Expressions
    • Automation Tools
    • VBScript Add-Ons
    • Printing Tools
    • Inventory Tools
    • Shell Extensions
    • File Viewers
    • Backup
    • Security
    • The making Of.
  • Miscellaneous
    • Tweaks
    • Hardware
      • VoltCraft Energy Logger 3500 Configuration
      • A Fast Compact Flash Card Reader
    • Link Speed Test
    • Web Stuff
    • Conversions
    • My Photo Galleries
  • About This Site
    • Disclaimer
    • News
    • FAQ
    • Search
    • What’s New
    • Objective
    • Advertising
    • Privacy Policy
    • Site Policy
    • Credits
    • The Making Of.
    • Contact
    • Failed Mail
    • Donate
Читайте также:  Execute shell scripts in windows

To make a batch file wait for a number of seconds there are several options available:

  • PAUSE
  • SLEEP
  • TIMEOUT
  • PING
  • NETSH (Windows XP/Server 2003 only)
  • CHOICE
  • CountDown
  • SystemTrayMessage
  • Other scripting languages
  • Unix ports
Note: Click a script file name to expand and view its source code; click the file name again, or the expanded source code, to hide the source code again.
To view the source code on its own, right-click the file name and choose Open or Open in separate tab or window.

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

Читайте также:  1c linux сервер пускает только 3 человек

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

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:

Оцените статью