设置 cmd 执行的超时时间 [英] Set time out for a cmd execution

查看:172
本文介绍了设置 cmd 执行的超时时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 cmd 执行需要很长时间,我想为它设置一个超时时间.超时后,我可以去下一行执行.是否可以?我的cmd是这样的.

I have a cmd execution takes too long time, I'd like to set a time out for it. After it's time out, then I can go to execute in next line. Is it possible? My cmd is like this.

example1.exe /e:dosomething. 
example2.exe /e:dosomething.

我想为example1.exe设置超时,然后我可以去执行example2.exe有什么方法吗?

I'd like to set time out for example1.exe, then I could go to execute example2.exe Any method?

推荐答案

改编自上一个回答,用于处理超时终止或继续运行进程的情况

Adapted from a previous answer to handle the cases of killing or keep running the process on timeout

@echo off
    setlocal enableextensions

    rem Case 1 - Start example 1 and kill it after 60 seconds
    start "" /b example1.exe /e:dosomething
    call :timeoutProcess "example1.exe" 60

    rem Test why execution continues
    if errorlevel 1 (
        echo Program has been killed
    ) else (
        echo Program has ended in time
    )

    rem Case 2 - Start example1 and after 60 seconds continue,
    rem          leaving example1 running
    start "" /b example1.exe /e:dosomething
    call :timeoutProcess "example1.exe" 60 1

    rem Test why execution continues
    if errorlevel 1 (
        echo Timeout - Program keeps running
    ) else (
        echo Program has ended in time
    )

    exit /b

:timeoutProcess process timeout [leave]
    rem process = name of process to monitor
    rem timeout = timeout in seconds to wait for process to end
    rem leave   = 1 if process should not be killed
    for /l %%t in (1 1 %~2) do (
        timeout.exe /t 1 >nul
        tasklist | find "%~1" >nul || exit /b 0
    )
    if not "%~3"=="1" taskkill /f /im "%~1" >nul 
    exit /b 1

这篇关于设置 cmd 执行的超时时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆