Batch file 批处理文件是否可以具有基于时间度量的if语句?

Batch file 批处理文件是否可以具有基于时间度量的if语句?,batch-file,Batch File,我正在尝试创建一个批处理文件,该文件只需在所需时间(5分钟)内吐出随机数(echo%random%),然后打开一个文件并退出批处理。 它看起来有点像这样: @echo off color a title "random number machine" cls :talk echo %random% %random% %random% %random% if [5 minutes has passed] ( start complete.vbs

我正在尝试创建一个批处理文件,该文件只需在所需时间(5分钟)内吐出随机数(echo%random%),然后打开一个文件并退出批处理。 它看起来有点像这样:

@echo off                
color a    
title "random number machine"
cls

:talk  
echo  %random% %random% %random% %random%   
if [5 minutes has passed] (
start complete.vbs  
exit ) || (
goto talk )

有人知道有没有可能制作这样的计时器吗?

有可能。您可以分析
%TIME%
环境变量。下面的脚本有点粗糙,因为它只使用了整秒,但是您也可以解析第四个标记(包含微秒),以获得更高的精度

@echo off
setlocal
color a
title "random number machine"
cls

:: Get starting time in seconds since midnight.
call :timestamp start

:talk
echo  %random% %random% %random% %random% 

:: Get current time in seconds since midnight.
call :timestamp now

:: Check for day wrap and correct if necessary
:: echo DEBUG: Timestamps = %now% and %start%
if %now% lss %start% set /a now=%now%+86400

:: Calculate difference in seconds
set /a diff=%now%-%start%
:: echo DEBUG: %diff% seconds have passed
if %diff% geq 5 (
  start complete.vbs  
  endlocal
  exit 
)

goto talk

:timestamp
setlocal EnableDelayedExpansion
for /f "tokens=1-3 delims=/:/ " %%a in ('echo %TIME%') do (
  :: Calculate the number of seconds since midnight, by multiplying the hour 
  :: and minute tokens with 3600 and 60 respectively.
  set /a timestamp=%%a * 3600 + %%b*60 + %%c
  :: echo DEBUG: %%a, %%b, %%c : !timestamp!
)
endlocal & set %~1=%timestamp%
goto :eof

实际上,可以在批处理文件中开发任何流程/任务;但是,如果问题很大,批处理文件的复杂性也会增加。换句话说:为大型通用应用程序编写批处理文件很困难,但为特定的小请求编写批处理文件相对简单

下面的批处理文件最多可等待59分钟:

@echo off                
color a    
title "random number machine"
cls

set waitMins=5

rem Get MM:SS from current time, add the number of waiting minutes
rem and reassemble the final time in MM:SS format:

set /A "futureMM=(1%time:~3,2%-100+waitMins) %% 60 + 100"
set "futureMMSS=%futureMM:~1%%time:~5,3%"

:talk  
echo  %random% %random% %random% %random%
if "%time:~3,5%" neq "%futureMMSS%" goto talk

echo %waitMins% minutes has passed

start complete.vbs  
exit
需要进行“复杂”算术计算,以消除分钟数中的左零;否则,
set/A
命令将发出一个错误(“无效八进制数”),时间为
08
09
分钟。当结果小于10时,最后的
+100
是插入左零的一种非常简单的方法