进程完成后超时或关闭 [英] timeout or close when process is finished
问题描述
我有一个X.exe
程序,大约需要2-6个小时才能完成.确切时间未知,但我想将阈值设置为6.5或7个小时.如果此程序在这段时间内没有返回任何值,它将被杀死.如何使用批处理*.bat
文件实施此操作?
I have a X.exe
program that takes about 2-6 hours to finish. Exact time is unknown, but I'd like to implement a threshold of 6.5 or 7 hours. If this program does not return any value by this amount of time, it will be killed. How do I implement this using batch *.bat
files?
这是我到目前为止的内容:一个计时器bat1.bat
和一个实际的bat2.bat
.
Here is what I had so far: a timer bat1.bat
and an actual bat2.bat
.
bat1.bat:
start cmd /C bat2.bat & timeout /t 25200 & taskkill /im X.exe /f
bat2.bat:
cd blah
bat1.bat
此方法的问题在于,只有在25200秒(或7个小时)之后,计时器才会停止运行,并且不会在该限制之前终止.我如何告诉计算机,如果X.exe
程序完成了,就不再等待了吗?
The problem with this approach is that only after 25200 seconds (or 7 hours) the timer will be stopped, and it won't be terminated before that limit. How do I tell the computer that if the program X.exe
is finished then don't wait anymore?
感谢您的帮助!
推荐答案
由于@Squashman,我能够自己构建脚本.似乎工作正常
thanks to @Squashman i was able to build a script on my own. seem to work fine
@echo off
setlocal enableextensions enabledelayedexpansion
set /a "checktime=60"
set /a "elapsedtime=0"
set /a "killtime=150"
set XProg=X.exe
start cmd /C runTest.bat
timeout /t 10
:while1
echo Go to WHILE loop.
echo elapsedtime = %elapsedtime%
echo killtime = %killtime%
set /a "timeleft = %killtime% - %elapsedtime%"
echo timeleft = %timeleft%
if /i %timeleft% geq 0 (
tasklist /fi "imagename eq %XProg%" 2>NUL | find /i /n "%XProg%">NUL
if "%ERRORLEVEL%"=="0" (
echo %XProg% is still running...
) else (
echo %XProg% is finished before timer.
)
set /a "elapsedtime = elapsedtime + checktime"
timeout /t %checktime%
goto :while1
) else (
taskkill /im %XProg% /f
echo %XProg% is terminated.
)
经验教训:
1.难以批量比较数值变量(将diff与0进行比较)
2.第一次终止elaspedtime > killtime
(可能会比killtime
长一些,具体取决于它检查的频率)
lessons learned:
1. hard to compare numeric variables in batch (compare diff with 0 instead)
2. terminated first time elaspedtime > killtime
(might be a bit longer than killtime
depending how often it checks)
这篇关于进程完成后超时或关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!