2015-07-11 56 views
2

我有這樣的代碼:使「矩陣」運行幾秒鐘?

:SET 
@echo %random%%random%%random%%random%%random%%random%%random%%random%%random% 

goto :SET 

但如何使它所以它只能運行幾秒鐘?我將如何改變這個變量?

回答

4

我得到%TIME%作爲當前時間,並解析它得到當前秒。我在循環的每次迭代中都做了它。如果所需時間沒有用在循環上(定義爲loopDuration),則繼續下一次迭代。

echo off 

:: Set your loop duration 
set /a loopDuration=2 

:: Get starting second 
set "startingTime=%TIME:~6,2%" 
set /a startingTime=%startingTime% 

:SET 

    echo %random%%random%%random%%random%%random%%random%%random%%random%%random% 

    :: Get current second 
    set "currentTime=%TIME:~6,2%" 
    set /a currentTime=%currentTime% 

    if %currentTime% lss %startingTime% (
     set /a currentTime=%currentTime% += 60 
    ) 

    set /a timePassed=%currentTime%-%startingTime% 

:: If desired time has not passed, continue the loop 
if not %timePassed% equ %loopDuration% (goto :SET) 

編輯:

我還檢查特例這裏感謝斯蒂芬。在這種情況下,如果startingTime的值爲59或接近60的值,那麼currentTime的值可能會小於startingTime。我用一個簡單的if語句來檢查它:

if %currentTime% lss %startingTime% (
    set /a currentTime=%currentTime%+=60 
) 

因此,currentTime不可能小於startingTime。除非你想讓你的循環運行超過59秒。

+2

用'xx:xx:59'的時間試試這個......這將會是兩個很長的時間。 – Stephan

+1

嗨,我可以把時間放在腳本中?謝謝你愛你的答案! – Cool841

+1

@ Cool841以秒爲單位的時間在變量'%loopDuration%'中。請注意,這隻能在不到60秒的時間內完成(這似乎完全符合您的要求) – Stephan