如何在指定时间后停止批处理脚本?

3

我正在编写一个批处理脚本,希望用户能够控制脚本运行的时间。当从命令行运行时,用户将传入一个开关,例如:

./myscript --stop-after 30

这意味着脚本将会继续执行它的任务并在每个循环中检查经过了多少时间。如果超过了半分钟,那么它会停止执行。我该如何在批处理脚本中实现这一功能?

以下是我目前的代码参考:

: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...
)

在解析选项之后,我该如何实施脚本的后半部分呢?

谢谢你的帮助。


这在很大程度上取决于长时间任务的性质。如果它是一些需要重复执行直到事件发生并且您可以让任务检测到该事件的操作,那么它将与需要强制终止的进程处理方式不同。 - Magoo
1个回答

4

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接