programing tip

배치 파일 / cmd에서 5 초 동안 잠자는 방법

itbloger 2020. 10. 2. 21:47
반응형

배치 파일 / cmd에서 5 초 동안 잠자는 방법 [중복]


이 질문에 이미 답변이 있습니다.

Windows의 캡처 도구는 화면을 캡처 할 수 있지만 때로는 웹캠에 표시되는 이미지를 찍는 것과 같이 5 초 후에 화면을 캡처하고 싶습니다. (예를 들어 스크립트를 실행하고 카메라에 미소를 지으십시오.)

배치 파일에서 5 초 동안 잠자는 방법은 무엇입니까?


한 가지 해킹은 ping 명령을 (잘못) 사용하는 것입니다.

ping 127.0.0.1 -n 6 > nul

설명:

  • pingping 요청을 보내는 시스템 유틸리티입니다. ping모든 버전의 Windows에서 사용할 수 있습니다.
  • 127.0.0.1localhost 의 IP 주소입니다 . 이 IP 주소는 항상 확인되고 연결 가능하며 ping에 즉시 응답하도록 보장됩니다.
  • -n 66 개의 핑이 있음을 지정합니다. 각 핑 사이에 1 초의 지연이 있으므로 5 초 지연의 경우 6 개의 핑을 보내야합니다.
  • > nul의 출력을 억제 ping하여, 재전송nul.

아무도 언급하지 않은 것에 놀랐습니다.

C:\> timeout 5

NB 그러나 timeout 5다음 의미합니다 (Dan에게 감사합니다!) .

4 초에서 5 초 사이의 수면

이것은 다음을 배치 파일에 넣고 반복적으로 실행하고 첫 번째와 두 번째 사이의 시간 차이를 계산하여 경험적으로 확인할 수 있습니다 echo.

@echo off
echo %time%
timeout 5 > NUL
echo %time%

Choice 명령을 시도하십시오 . MSDOS 6.0 이후로 사용되어 왔으며 트릭을 수행해야합니다.

/ T 매개 변수를 사용하여 시간 제한 (초)을 지정하고 / D 매개 변수를 사용하여 기본 선택을 지정하고 선택한 선택을 무시합니다.

문제가 될 수있는 한 가지는 제한 시간이 경과하기 전에 사용자가 선택 문자 중 하나를 입력하는 경우입니다. 부분적인 해결 방법은 상황을 난독 화하는 것입니다. / N 인수를 사용하여 유효한 선택 목록을 숨기고 선택 항목 집합에 1 개의 문자 만 있으면 사용자가 해당 항목 앞에 유효한 선택 항목을 입력 할 가능성이 줄어 듭니다. 시간 초과가 만료됩니다.

다음은 Windows Vista의 도움말 텍스트입니다. XP에서도 동일하다고 생각하지만 XP 컴퓨터에서 도움말 텍스트를 확인하여 확인하십시오.

C:\>CHOICE /?

CHOICE [/C choices] [/N] [/CS] [/T timeout /D choice] [/M text]

Description:
    This tool allows users to select one item from a list
    of choices and returns the index of the selected choice.

Parameter List:
   /C    choices       Specifies the list of choices to be created.
                       Default list is "YN".

   /N                  Hides the list of choices in the prompt.
                       The message before the prompt is displayed
                       and the choices are still enabled.

   /CS                 Enables case-sensitive choices to be selected.
                       By default, the utility is case-insensitive.

   /T    timeout       The number of seconds to pause before a default
                       choice is made. Acceptable values are from 0 to
                       9999. If 0 is specified, there will be no pause
                       and the default choice is selected.

   /D    choice        Specifies the default choice after nnnn seconds.
                       Character must be in the set of choices specified
                       by /C option and must also specify nnnn with /T.

   /M    text          Specifies the message to be displayed before
                       the prompt. If not specified, the utility
                       displays only a prompt.

   /?                  Displays this help message.

   NOTE:
   The ERRORLEVEL environment variable is set to the index of the
   key that was selected from the set of choices. The first choice
   listed returns a value of 1, the second a value of 2, and so on.
   If the user presses a key that is not a valid choice, the tool
   sounds a warning beep. If tool detects an error condition,
   it returns an ERRORLEVEL value of 255. If the user presses
   CTRL+BREAK or CTRL+C, the tool returns an ERRORLEVEL value
   of 0. When you use ERRORLEVEL parameters in a batch program, list
   them in decreasing order.

Examples:
   CHOICE /?
   CHOICE /C YNC /M "Press Y for Yes, N for No or C for Cancel."
   CHOICE /T 10 /C ync /CS /D y
   CHOICE /C ab /M "Select a for option 1 and b for option 2."
   CHOICE /C ab /N /M "Select a for option 1 and b for option 2."

다음 해킹은 5 초 동안 잠들게합니다

ping -n 6 127.0.0.1 > nul

핑은 핑 사이에 1 초간 대기하므로 필요한 것보다 하나 더 지정해야합니다.


다음으로 만들 수 있습니다 timeout.

다음과 같이 표시됩니다. timeout 5

이것은 보이지 않을 것입니다 timeout 5 >nul


당신이 가지고있는 경우에 PowerShell을 시스템에, 당신은이 명령을 실행할 수 있습니다 :

powershell -command "Start-Sleep -s 5"

편집 : 사람들은 당신이 기다리는 시간에 비해 powershell이 ​​시작하는 데 걸리는 시간이 중요한 문제를 제기했습니다. 대기 시간의 정확성이 중요한 경우 (예 : 1 초 또는 2 초의 추가 지연이 허용되지 않음) 다음 방법을 사용할 수 있습니다.

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

이것은 windows 명령이 실행될 때 시간이 걸리며 powershell 스크립트는 그 시간 이후 5 초까지 휴면 상태가됩니다. 따라서 powershell이 ​​수면 시간보다 시작하는 데 시간이 덜 걸리는 한이 방법은 작동합니다 (내 컴퓨터에서 약 600ms).


우리는 할 수 없습니까 waitfor /T 180?

waitfor /T 180 pause "오류 : '일시 중지'대기 시간이 초과되었습니다."가 발생합니다.

waitfor /T 180 pause >nul 양탄자 아래에서 그 "오류"를 쓸 것입니다

waitfor명령 Win95는 후 Windows OS에서이 있어야한다

과거에는 sleep경로에 넣은 후 명령 줄에서 작동하는 이름의 실행 파일을 다운로드했습니다 .

예를 들어 : sleep shutdown -r -f /m \\yourmachineshutdown에는 이제 -t 옵션이 내장되어 있지만


Timeout /t 1 >nul

1 초 후에 일시 중지하는 것과 같습니다. 라임을 거의 100.000 (99.999) 초까지 가져올 수 있습니다. 인터넷에 연결되어있는 경우 최상의 솔루션은 다음과 같습니다.

ping 1.1.1.1. -n 1 -w 1000 >nul

핑할 때 밀리 초 단위로 계산하므로 1 초는 1000 밀리 초가됩니다. 그러나 ping 명령은 약간 불명확하며 오프라인 시스템에서는 동일한 방식으로 작동하지 않습니다. 문제는 머신이 오프라인 상태이기 때문에 혼란스럽고 ping을하려고 website/server/host/ip하지만 할 수 없다는 것입니다. 그래서 시간 제한을 권장합니다. 행운을 빕니다!


SLEEP 5 일부 Windows Resource Kit에 포함되었습니다.

TIMEOUT 5 일부 Windows Resource Kit에 포함되었지만 이제는 Windows 7 및 8의 표준 명령입니다 (Vista에 대해서는 확실하지 않음).

PING 1.1.1.1 -n 1 -w 5000 >NUL TCP / IP 클라이언트가있는 MS-DOS 또는 Windows 버전의 경우 PING을 사용하여 몇 초 동안 실행을 지연시킬 수 있습니다.

NETSH badcommand (Windows XP / Server 2003 만 해당) 또는 CHOICE

이 링크는 더 많은 도움이 될 것 입니다.


두 가지 답변 :

첫째, 사람들이 제안한 모든 둔한 방법없이 배치 파일을 지연시키는 것입니다.

timeout /t <TimeoutInSeconds> [/nobreak] 

http://technet.microsoft.com/en-us/library/cc754891.aspx

둘째, 내장 된 Windows 캡처 도구를 사용하여 원하는 작업을 정확히 수행하지 못할 수도 있지만 마우스를 사용하지 않고도 캡처를 트리거 할 수 있습니다. 캡처 도구를 실행하고 현재 캡처에서 벗어나지 만 도구를 실행 한 상태로두고 캡처가 발생하도록하려면 Control + Print Screen 키를 누르십시오. 이것은 당신이 자르려는 것이 무엇이든 방해해서는 안됩니다.


msbuild 작업 내에서이 작업을 수행하려고했는데 I / O 리디렉션으로 인해 선택 및 시간 초과가 모두 작동하지 않았습니다.

http://sourceforge.net/projects/unxutils 에서 sleep.exe를 사용하게되었습니다 . 설치가 필요없고 크기가 작기 때문에 좋습니다.


시도 choice:

<Target Name="TestCmd">
  <Exec Command="choice /C YN /D Y /t 5 " />
</Target>

결과 :

TestCmd:
  choice /C YN /D Y /t 5

EXEC : error : The file is either empty or does not contain the valid choices. [test.proj]
  [Y,N]?
C:\test.proj(5,9): error MSB3073: The command "choice /C YN /D Y /t 5 " exited with code 255.

시도 timeout:

<Target Name="TestCmd">
  <Exec Command="timeout /t 5 " />
</Target>

결과 :

TestCmd:
  timeout /t 5
EXEC : error : Input redirection is not supported, exiting the process immediately. [test.proj]
C:\test.proj(5,7): error MSB3073: The command "timeout /t 5 " exited with code 1.

곁에:

나는 <Exec Command="sleep 2 & dbghost.exe" />dbghost.exe를 병렬로 여러 번 실행하고 현재 epoch 시간 (초)을 기반으로 임시 파일 / 데이터베이스를 생성하기 때문에 실제로 사용 하고 있습니다. 물론 여러 인스턴스를 시작하면 각각 동일한 임시 이름을 사용합니다. 원래 MSBuild Extension Pack Thread.Sleep명령 을 사용하려고 시도 했지만 (일반적으로) 절전 작업을 정상적으로 실행하고 <exec>있는 것 같지만 동시에 모든 스레드에서 작업 을 시작하고 물론 dbghost.exe가 충돌로 실패합니다. 지금까지 sleep.exe를 사용하는 것이 더 안정적인 것 같습니다.


XP 이상의 모든 항목에서 작동하는 두 가지 방법이 더 있습니다.

w32tm 사용

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

typeperf로 :

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

이것은 스크립트가 끝날 때 출력을보기 위해 10 초 동안 실제로 사용하고있는 최신 버전입니다.

BEST>@echo done
BEST>@set DelayInSeconds=10
BEST>@rem Use ping to wait
BEST>@ping 192.0.2.0 -n 1 -w %DelayInSeconds%000 > nul

완료된 에코를 통해 스크립트가 언제 완료되었는지 확인할 수 있으며 핑이 지연을 제공합니다. 추가 @ 기호는 "완료"텍스트가 표시되고 명령에 방해받지 않고 대기가 발생 함을 의미합니다.

저는 여기에 제시된 다양한 솔루션을 XP 시스템에서 시도했습니다. 그 아이디어는 다양한 시스템에서 실행되는 배치 파일을 갖는 것이었기 때문에 XP 시스템을 성능이 가장 낮은 환경으로 선택했습니다.

GOOD> ping 192.0.2.0 -n 1 -w 3000 > nul

예상대로 3 초 지연되는 것 같았습니다. 지정된 3 초 동안 한 번의 핑 시도.

BAD> ping -n 5 192.0.2.0 > nul

약 10 초 (5 초가 아님)가 소요되었습니다. 내 설명은 각각 약 1 초 간격으로 4 초 동안 5 번의 핑 시도가 있다는 것입니다. 그리고 각 핑 시도는 약 1 초 동안 지속되어 총 9 초로 추정됩니다.

BAD> timeout 5
BAD> sleep /w2000
BAD> waitfor /T 180
BAD> choice

명령을 사용할 수 없습니다.

BAD> ping 192.0.2.0 -n 1 -w 10000 > nul :: wait 10000 milliseconds, ie 10 secs

두 개의 연속 콜론을 사용하여 BAT 파일에 주석을 추가 할 수 있음을 읽은 후 위도 시도했습니다. 그러나 소프트웨어는 거의 즉시 반환되었습니다. 핑이 제대로 작동하기 전에 자체 줄에 주석을 추가했습니다.

GOOD> :: wait 10000 milliseconds, ie 10 secs
GOOD> ping 192.0.2.0 -n 1 -w 10000 > nul

실제로 ping이 수행하는 작업을 더 잘 이해하기 위해

ping 192.0.2.0 -n 5 -w 5000

5 * 5 = 25인데도 약 30 초가 걸렸습니다. 내 설명은 각각 5 초 동안 5 번의 핑 시도가 있지만 핑 시도 사이에 약 1 초의 시간 지연이 있다는 것입니다. 즉시 다시 핑하면 다른 결과를 기대할 이유가 거의 없으며 네트워크가 가지고있는 문제를 복구하는 데 약간의 시간이 걸립니다.

편집 : 다른 게시물 에서 도난당했습니다 . .. RFC 3330 은 IP 주소 192.0.2.0이 인터넷에 나타나지 않아야한다고 말합니다. 따라서이 주소를 핑하면 이러한 테스트가 스팸을 보내는 것을 방지 할 수 있습니다! 그에 따라 위의 텍스트를 수정했습니다!


나는 이것을 만들었다. 작동하고 남은 시간을 초 단위로 표시합니다. 사용하려면 배치 파일에 추가하십시오.

call wait 10

내가 그것을 테스트했을 때 작동했습니다.

목록 wait.bat(작업 디렉토리 또는에 있어야 함 windir/system32/) :

@echo off

set SW=00

set SW2=00

set /a Sec=%1-1

set il=00
@echo Wait %1 second
for /f "tokens=1,2,3,4 delims=:," %%A in ("%TIME%") do set /a HH=%%A, MM=1%%B-100, SS=1%%C-100, CC=1%%D-100, TBASE=((HH*60+MM)*60+SS)*100+CC, SW=CC 

set /a TFIN=%TBASE%+%100

:ESPERAR
for /f "tokens=1,2,3,4 delims=:," %%A in ("%TIME%") do set /a HH=%%A, MM=1%%B-100, SS=1%%C-100, 

CC=1%%D-100, TACTUAL=((HH*60+MM)*60+SS)*100+CC,  SW2=CC


if %SW2% neq %SW% goto notype
if %il%==0 (echo Left %Sec% second & set /a Sec=sec-1 & set /a il=il+1)
goto no0
:notype
set /a il=0
:no0

if %TACTUAL% lss %TBASE% set /a TACTUAL=%TBASE%+%TACTUAL%
if %TACTUAL% lss %TFIN% goto ESPERAR

VBScript 를 사용할 수 있습니다 ( myscript.vbs: file :

set wsobject = wscript.createobject("wscript.shell")

do while 1=1
    wsobject.run "SnippingTool.exe",0,TRUE
    wscript.sleep 3000
loop

배치 파일:

cscript myscript.vbs %1

사용자 Aacini가 제안한 코드의 개선으로, 100 분의 1 초의 해상도를 가지며 시간이 23 : 59 : 59,99에 도달해도 실패하지 않습니다.

for /f "tokens=1,2,3,4 delims=:," %%A in ("%TIME%") do set /a HH=%%A, MM=1%%B-100, SS=1%%C-100, CC=1%%D-100, TBASE=((HH*60+MM)*60+SS)*100+CC

:: Example delay 1 seg.
set /a TFIN=%TBASE%+100

:ESPERAR
for /f "tokens=1,2,3,4 delims=:," %%A in ("%TIME%") do set /a HH=%%A, MM=1%%B-100, SS=1%%C-100, CC=1%%D-100, TACTUAL=((HH*60+MM)*60+SS)*100+CC

if %TACTUAL% lss %TBASE% set /a TACTUAL=%TBASE%+%TACTUAL%
if %TACTUAL% lss %TFIN% goto ESPERAR

배치 파일에서 지연을 수행하기 위해 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

You may also insert the day in the calculation so the method also works when the delay interval pass over midnight.


The easiest way I did it was this:

Download the Sleep.exe at http://www.sleepcmd.com/. The .exe file should be in the same folder as the program you wrote!


It can be done with two simple lines in a batch file: write a temporary .vbs file in the %temp% folder and call it:

echo WScript.Sleep(5000) >"%temp%\sleep.vbs"
cscript "%temp%\sleep.vbs"

If you have an appropriate version of Windows and the Windows Server 2003 Resource Kit Tools, it includes a sleep command for batch programs. More at: http://malektips.com/xp_dos_0002.html


PING -n 60 127.0.0.1>nul

in case your LAN adapter is not available.


In Windows xp sp3 you can use sleep command


Make a cmd file called sleep.cmd:

REM Usage: SLEEP Time_in_MiliSECONDS
@ECHO off
ping 1.0.0.0 -n 1 -w %1 > nul

Copy sleep.cmd to c:\windows\system32

Usage:

sleep 500

Sleeps for 0.5 seconds. Arguments in ms. Once copied to System32, can be used everywhere.

EDIT: You should also be away that if the machine isn't connected to a network (say a portable that your using in the subway), the ping trick doesn't really work anymore.


Well this works if you have choice or ping.

@echo off
echo.
if "%1"=="" goto askq
if "%1"=="/?" goto help
if /i "%1"=="/h" goto help
if %1 GTR 0 if %1 LEQ 9999 if /i "%2"=="/q" set ans1=%1& goto quiet
if %1 GTR 0 if %1 LEQ 9999 set ans1=%1& goto breakout
if %1 LEQ 0 echo %1 is not a valid number & goto help
if not "%1"=="" echo.&echo "%1" is a bad parameter & goto help
goto end

:help
echo SLEEP runs interactively (by itself) or with parameters (sleep # /q )
echo where # is in seconds, ranges from 1 - 9999
echo Use optional parameter /q to suppress standard output 
echo or type /h or /? for this help file
echo.
goto end

:askq
set /p ans1=How many seconds to sleep? ^<1-9999^> 
echo.
if "%ans1%"=="" goto askq
if %ans1% GTR 0 if %ans1% LEQ 9999 goto breakout
goto askq

:quiet
choice /n /t %ans1% /d n > nul
if errorlevel 1 ping 1.1.1.1 -n 1 -w %ans1%000 > nul
goto end

:breakout
choice /n /t %ans1% /d n > nul
if errorlevel 1 ping 1.1.1.1 -n 1 -w %ans1%000 > nul
echo Slept %ans1% second^(s^)
echo.

:end

just name it sleep.cmd or sleep.bat and run it


ping waits for about 5 seconds before timing out, not 1 second as was stated above. That is, unless you tell it to only wait for 1 second before timing out.

ping 1.0.0.1 -n 1 -w 1000

will ping once, wait only 1 second (1000 ms) for a response, then time out.

So an approximately 20-second delay would be:

ping 1.0.0.1 -n 20 -w 1000


I wrote a powerbasic program wait.exe, where you pass a millisecond parameter to it in your batch file

wait 3000
system('c:/windows/system32/SnippingTool.exe')

the code for the EXE:

FUNCTION PBMAIN()
  c$ = Command$
  s! = Val(c$)*1000
  Sleep s!         
END FUNCTION

On newer Windows OS versions you can use the command

sleep /w2000

in a DOS script (.cmd or .bat) to wait for 2s (2000 ms - substitute the time in ms you need). Be careful to include the /w argument - without it the whole computer is put to sleep! You can use -m instead of /m if you wish and optionally a colon (:) between the w and the number.


This should do the trick: choice /T 5 /N /D Y

Replace the 5 with the time in seconds you want to wait...


There is!

SLEEP <seconds>

If you want it in millisecond mode:

SLEEP -m <time in milliseconds>

This is more helpful than TIMEOUT because TIMEOUT can be aborted with a click of a key or CTRL + C (for TIMEOUT /t <secs> /nobreak). SLEEP cannot be aborted by anything (except for close button :p)

Other one is PING. But PING needs internet connection because you'll be recording the connection of a site.


I think the following command can help:

pause 5

The syntax of the pause command is: pause d \\where d represents the duration in seconds

I am using Windows 7 (32 bit), but I don't know about the others.

참고URL : https://stackoverflow.com/questions/1672338/how-to-sleep-for-five-seconds-in-a-batch-file-cmd

반응형