Жизнь без алкоголя запойного алкоголика | Родная душа – статьи, компьютер, Интернет | Создание, оптимизация сайтов, блогов | 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-файл,
запустить и посмотреть, как это работает.
Впечатляет.
Как сделать задержку в командном файле
wikiHow работает по принципу вики, а это значит, что многие наши статьи написаны несколькими авторами. При создании этой статьи над ее редактированием и улучшением работали, в том числе анонимно, 10 человек(а).
Количество просмотров этой статьи: 44 971.
Из этой статьи вы узнаете, как предотвратить немедленный запуск пакетного файла, когда его открывают. Есть несколько различных команд, которые можно использовать для задержки пакетного файла. Имейте в виду, что вы должны хорошо знать, как создавать пакетные файлы, прежде чем пытаться сделать его задержку.
Как сделать задержку в 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):
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:
How to sleep or wait in Windows batch file ?
The Sleep/Wait Command is a very useful command that is used to pause for a set amount of time while a batch script is being executed. To put it another way, this command makes it easier to run a command for a set amount of time.
Table of Contents
You may find yourself in a situation where you want to run a series of command lines one after the other, but with a time delay between them. In this case, the sleep command will come in handy. This article will show you how to use the sleep command in Windows batch scripts. fig. Sleep and wait
1 Using timeout to achieve sleep function
Please enable JavaScript
Example1: Basic timeout in Batch Script
We have two tasks here, and we have inserted a timeout script that waits for 10 seconds for the First Task to complete before starting the Second Task.
«@echo off» disables the console window command display in this Windows batch file script. After this line, console commands will not be displayed.
The terminal window will display «echo First Task Here» after the next line. Displays the provided text in the console window.
«echo About 10-second delay» informs the user of a delay in the console window.
«Timeout /t 10» will postpone script execution for 10 seconds. The console window will countdown the remaining time.
«echo Second Task Here. » will appear in the terminal window after the wait, restarting script execution.
Lastly, the «pause» command pauses script execution and displays «Press any key to resume. «, allowing the user to inspect the console window output before closing it. After «pause,» the script must be resumed by pressing any key.
Drawback: This will show unnecessary «Waiting for 0 seconds, press a key to continue. » and when you press any key it will continue to the next task. It is a good way of letting the user know the safe escape route to skip sleep.
Example2: Timeout with only CTRL + C key to Skip
H ere, /nobreak does not allow to break or skip sleep with any key. But pressing the CTRL + C key combination will force to close the batch processing and close the program immediately.
Example 3: Sleep without timeout message
Appending >nul part so that the command does not display output anything to the screen. It suppresses the countdown time.
Another best use case of the timeout is as follows:
This will open the calculator, then wait 5 seconds before opening the notepad. Remember to include and && between each block. You can continue to cascade it like shown below
This will open the calculator, then wait 3 seconds for the notepad to open, then wait 4 seconds for the registry editor to open.
Drawbacks of TIMEOUT
- Cannot perform delay in a fraction of a second. ie. like timeout /t 0.5 does not work. And will give
an error message stating «Error: Invalid value for timeout (/T) specified. The valid range is -1 to 99999) - Cannot use a second value greater than 99999
2 Using Ping to Delay to achieve sleep function
Ping is actually used to determine whether or not a resource responds to a request. Ping sends a request to the resource and waits one second for a response. As a result, it is useful to use it as a delay function. Even if it waits for one second, it may receive a response in a few milliseconds. However, as soon as you ping the last packet here in the tenth request, it will automatically stop.
The resource we are pinging here is localhost, which is a local loopback, and it responds instantly within a millisecond but must wait 1 second each. And here in the example, we are waiting for nearly 10 seconds before executing the next line.
3 Using Ping to Delay with nonexisting IP
Here waiting for 10 seconds. Here we must ping a non-existing IP address and if it exists it will not work. -w indicates waiting and here it waits for 10000 ms, you can change this value. And by default ping will request 4 times to the resource. Here, -n 1 indicates request only 1 time.
4 Using Ping to Delay in less than 1 second.
Just replace 10000ms with anything smaller than 1000ms. like 500ms as shown below
5 Using Powershell in Command to delay
Simply follow the simple example below if you want to use Powershell commands from the command line:
type this command in the command line or batch file. This command will hold the screen for 5 seconds. You can change it from 5 to any number. This can be useful if a Windows command fails or has an issue.
6 Using Powershell in Sleep Start Command to delay
Alternatively, you can sleep-start command of Powershell in CMD as below:
The above command will wait for 5 seconds. Note that: Method 5 is a short form of method 6
The above command will wait for 500 milliseconds.
7 Using the Mshta command
Mshta.exe is a native Windows binary that was developed specifically for the purpose of executing Microsoft HTML Application (HTA) files.Mshta is able to run code written in Windows Script Host (VBScript and JScript) that is embedded into HTML in a manner that is aware of network proxies.
Conclusion:
To summarize, in Windows batch files, you can pause the execution of the batch file for a specified number of seconds by using the «sleep» command, and you can create a custom «wait» command by using the «timeout» command. Both of these commands can be found in the «commands» section of the batch file. While the «wait» command can be used to wait for a defined number of seconds before continuing with the next command, the «sleep» command is used to pause the execution of the batch file for a specified number of seconds at a time. You will be able to regulate the timing and flow of your batch file by using these commands, which will enable you to ensure that it runs smoothly and effectively.
Waitfor.exe is a small utility that is included with Windows 7 and later versions. This program is designed to listen for and respond to a named signal. Visit here for more info.
There is no sleep and wait-for command in the windows version. The best alternative is the Timeout command as explained above. In Linux, you can simply use: sleep n in the terminal where n is time in seconds.
A simple way to do this in a batch file before and after the task you want to sleep or hold is as follows: