批处理文件 - "the matrix"运行几秒钟?



我有这样的代码:

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

但是我如何使它只运行几秒钟呢?我怎么改变这个变量呢?

我将%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)
编辑:

感谢Stephan,我还检查了这里的一个特殊情况。在这种情况下,如果startingTime的值为59或接近60,那么currentTime的值很可能小于startingTime。我用一个简单的if语句检查了一下:

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

所以currentTime不可能小于startingTime。除非你想让你的循环运行超过59秒

最新更新