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

时间:2015-07-31 21:52:40

标签: batch-file

我试图制作批量文件,只需将随机数(回显%随机%)吐出所需时间(5分钟),然后打开文件并退出批处理。 看起来有点像这样:

@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 )

有谁知道是否可以制作这样的计时器?

2 个答案:

答案 0 :(得分:3)

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

下面的批处理文件可以等待最多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命令会在0809分钟内发出错误(“无效的八进制数”)。最终+100是一种在结果小于10时插入左零的非常简单的方法。

答案 1 :(得分:2)

有可能。您可以解析%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