天天看點

DOS批處理延時執行方案總結

偶爾會用到,今天就總結幾個批處理延時執行指令的方案。

需求:延時5秒打開test.txt這個檔案

方案1:ping指令 缺點:時間精度約為1秒,延時越久誤差越大,不夠精确

@echo off 
@ping 127.0.0.1 -n 6 >nul
start test.txt
           

方案2-(1):VBScript和start /wait指令 缺點:附帶生成臨時檔案 有點:時間精度約為0.001秒,精度高

@echo off
echo wscript.sleep 5000><span style="color: rgb(51, 51, 51); font-family: 宋體; font-size: 14px; line-height: 28px;">%tmp%\</span>sleep.vbs
start /wait sleep.vbs
start test.txt 
del /f /s /q <span style="color: rgb(51, 51, 51); font-family: 宋體; font-size: 14px; line-height: 28px;">%tmp%\</span>sleep.vbs
           

方案2-(2):VBScript

@echo off 
echo wscript.sleep 5000><span style="color: rgb(51, 51, 51); font-family: 宋體; font-size: 14px; line-height: 28px;">%tmp%\</span>sleep.vbs
@cscript sleep.vbs >nul
start test.txt 
del /f /s /q <span style="color: rgb(51, 51, 51); font-family: 宋體; font-size: 14px; line-height: 28px;">%tmp%\</span>sleep.vbs
           

方案3:choice指令 優點:時間精确,CPU占用低。最佳選擇 

@echo off 
choice /t 5 /d y /n >nul
start test.txt
           

方案4:call指令 缺點:準确度受CPU頻率影響很大,不夠精确,占用記憶體較多

@echo off
:loop
    echo %time%
    call :delay 1000
    echo %time%
goto loop
:delay
    set /a num=num + 1
    if %num% geq %1 (set num=) && goto :eof
rem    for /l %%i in (1,1,%1) do echo. >nul
goto :eof
start test.txt
           

方案5:msg指令 缺點:記憶體占用非常大,有視窗彈出

@echo off
msg %username% /time:5000 /w "正在延時,點确定可以取消延時!"
start test.txt