2012-09-12 120 views

回答

2

我刚刚安装了Cygwin并使用了unix-style timeout命令。

0

我不认为有超时命令。但是,您可以开始在后台执行任务并在超时时间内使用ping(使用ping),然后终止任务。

+0

“* using ping *”是什么意思? –

+0

http://stackoverflow.com/a/735294/390913 – perreal

4

要限制某个程序运行,你可以做这样的事情

start yourprogram.exe 
timeout /t 10 
taskkill /im yourprogram.exe /f 

启动yourprogram.exe,等待10秒时间,然后杀死该程序。

+1

这不是我想要的。Unix'timeout'命令允许限制程序/脚本/命令的执行时间。 –

+0

啊对了,对不起,我以前从未使用过Unix。我已经更新了我的答案,希望能回答你的问题。 –

+1

实际上程序执行可能需要10分钟到3-4小时。我想限制这个时间到2小时。所以当应用程序在10分钟内完成时,我不希望批量作业等待1小时50分钟。有什么建议么? –

0

此代码等待60秒,然后检查%ProgramName%是否正在运行。

要增加此时间,请更改WaitForMinutes的值。

要缩短检查之间的时间间隔,请将WaitForSeconds设置为希望等待的秒数。

@echo off 
set ProgramName=calc.exe 
set EndInHours=2 

:: How Many Minutes in between each check to see if %ProgramName% is Running 
:: To change it to seconds, just set %WaitForSeconds% Manually 
set WaitForMinutes=1 
set /a WaitForSeconds=%WaitForMinutes%*60 

:: How many times to loop 
set /a MaxLoop=(%EndInHours%*60*60)/(%WaitForMinutes%*60) 

REM Use a VBScript popup window asking to terminate %ProgramName% 
echo set WshShell = WScript.CreateObject("WScript.Shell") > %tmp%\tmp.vbs 
echo Wscript.Quit (WshShell.Popup("Click 'OK' to terminate %ProgramName%." ,10 ,"Terminate %ProgramName%", 0)) >> %tmp%\tmp.vbs 

start %ProgramName% 
set running=True 
:: Give time for %ProgramName% to launch. 
timeout /t 5 /nobreak > nul 
setlocal enabledelayedexpansion 
for /l %%x in (1,1,%MaxLoop%) do (
    if "!running!"=="True" for /l %%y in (1,1,%WaitForMinutes%) do (
    if "!running!"=="True" (
     set running=False 
     REM call Pop-Up 
     cscript /nologo %tmp%\tmp.vbs 
     if !errorlevel!==-1 (
     for /f "skip=3" %%x in ('tasklist /fi "IMAGENAME EQ %ProgramName%"') do set running=True 
    ) else (
     taskkill /im %ProgramName% 
    ) 
    ) 
) 
) 
if exist %tmp%\tmp.vbs del %tmp%\tmp.vbs 

该代码使用VBScript创建一个弹出框。单击OK将导致%ProgramName%通过taskkill被杀死。


如果你不想使用弹出窗口,可以通过删除使用timeout ...

REM Use a VBScript popup window asking to terminate %ProgramName% 
echo set WshShell = WScript.CreateObject("WScript.Shell") > %tmp%\tmp.vbs 
echo Wscript.Quit (WshShell.Popup("Click 'OK' to terminate %ProgramName%." ,10 ,"Terminate %ProgramName%", 0)) >> %tmp%\tmp.vbs 

...和更换此...

 REM call Pop-Up 
     cscript /nologo %tmp%\tmp.vbs 
     if !errorlevel!==-1 (

...这一点:

 REM Use CTRL+C to kill %ProgramName% 
     timeout /t %WaitForSeconds% /nobreak 
     if !errorlevel!==0 (

使用/nobreak是必要的,因为timeout不区分按键或超时。这将允许您通过按CTRL + C终止%ProgramName%,但这会导致您的批处理文件在您执行操作时询问Terminate batch job (Y/N)?。 Sl//凌乱/讨厌恕我直言。


你可以代替用此来替换上面的代码中使用CHOICE

 REM Using choice, but choice can get stuck with a wrong keystroke 
     Echo [K]ill %ProgramName% or [S]imulate %WaitForSeconds% Seconds 
     Choice /n /c sk /t %WaitForSeconds% /d s 
     if !errorlevel!==1 (

不过的选择带来了它自己的一套限制表中的。首先,如果一个不在其选项中的按键(在这种情况下为sk)被按下,它将停止倒计时,基本上锁定直到做出正确的选择。其次,SPACEBAR不能作为选择。

+0

如果我使用不同的启动和执行时间启动多个实例,该怎么办? –