在指定的时间之后停止批处理脚本的最佳方法是什么?

我正在写一个批处理脚本,我希望用户能够控制脚本运行的时间。 当从命令行运行它时,用户将像这样传递一个开关:

./myscript --stop-after 30 

这意味着脚本将继续工作,并检查每一次迭代已经过了多less时间。 如果超过半分钟过去了,那么它就会退出。 我将如何在批处理脚本中执行此操作?

作为参考,这里是我到目前为止的代码:

 :parseArgs if "%~1" == "" goto doneParsing if /i "%~1" == "--stop-after" ( shift set "duration=%~1" ) :: Parse some other options... shift goto parseArgs :doneParsing :: Now do the actual work (psuedocode) set "start=getCurrentTime" set "end=%start% + %duration%" while getCurrentTime < %end% ( :: Do some lengthy task... ) 

在parsing选项后,我将如何去执行脚本的后半部分?

感谢您的帮助。

这不是那么简单。 您必须在脚本中进行大量计算,以涵盖所有分钟,整整一小时甚至是新的一天的所有情况。 我可以想到两种不同的方式。 两者都基于两个批处理文件:

1.通过任务taskkill终止

starter.bat

 @echo off if "%1"=="" ( set duration=5 ) else ( set duration=%1 ) start "myscript" script.bat ping 127.0.0.1 -n %duration% -w 1000 > nul echo %duration% seconds are over. Terminating! taskkill /FI "WINDOWTITLE eq myscript*" pause 

script.bat

 @echo off :STARTLOOP echo doing work ping 127.0.0.1 -n 2 -w 1000 > nul goto STARTLOOP 

对于这个解决方案,重要的是你要让窗口执行你的脚本里面一个唯一的名字,在行start "myscript" script.bat 。 在这个例子中,名字是myscripttaskkill /FI "WINDOWTITLE eq myscript*"使用myscript来标识哪个进程终止。

但是,这可能有点危险。 无论迭代是否完成,你的脚本都会在x秒后被杀死。 所以, 例如 ,写访问将是一个坏主意。

2.通过标志文件终止

starter.bat

 @echo off if "%1"=="" ( set duration=5 ) else ( set duration=%1 ) if exist terminationflag.tmp del terminationflag.tmp start script.bat ping 127.0.0.1 -n %duration% -w 1000 > nul echo %duration% seconds are over. Setting termination flag! type NUL>terminationflag.tmp 

script.bat

 @echo off :STARTLOOP echo doing work ping 127.0.0.1 -n 2 -w 1000 > nul if not exist terminationflag.tmp goto STARTLOOP del terminationflag.tmp echo terminated! 

在这里,确保您的脚本被允许在当前位置创建/删除文件是很重要的。 这个解决方案更安全。 起始脚本将等待给定的时间,然后创建标志文件。 您的脚本将在每次完整迭代后检查标志是否存在。 如果不是,则会继续 – 如果是,则会删除标记文件并安全终止。

在这两种解决方案中, ping用作超时功能。 如果您在Windows 2000或更高版本上,也可以使用timeout/t <TimeoutInSeconds> 。 但是, timeout并不总是工作。 它会在某些计划任务,构建服务器和其他许多情况下失败。 你最好建议坚持ping