How to specify timeout for script?
Maybe you run into this issue before - you want to run some script/utility (for example query user), but you know that it hangs sometimes and you would like to have some kind of timeout utility. There is way how to handle this in batch scripts using two concurent scripts:
Create three scripts, for example Scripts.cmd, Pause.cmd and Detection.cmd
Content of Script.cmd is
Set Int.Command=%~1
Set Int.Pause=%~2
Set Int.PauseTitle=%Random%PauseScript
Set Int.DetectionTitle=%Random%DetectionScript
Start /Min Cmd /c Detection.cmd
Start cmd /c exit /b 1
Start /Min /Wait cmd /c Pause.cmd
If %ErrorLevel% EQU 0 (
Echo Failure
) Else (
Echo Success
)
Content of Pause.cmd is
Title %Int.PauseTitle%
Sleep %Int.Pause%
Taskkill /f /t /fi "WINDOWTITLE eq %Int.DetectionTitle%"
Content of Detection.cmd is
Title %Int.DetectionTitle%
%Int.Command%
Taskkill /f /t /fi "WINDOWTITLE eq %Int.PauseTitle%"
Exit /b 0
Then call Script.cmd with two arguments, command to perform and timeout. For example Script.cmd "pause" "10".
It will try to execute command "Pause", and if it took more then 10 seconds, it will kill this process and report it using errorlevel.
Quite simple, however functional. This way it is also fast, because if your scripts finished faster, it will automatically remove Sleep subroutine that will hold main script execution.
I am using this procedure right now to detect hanging sessions on servers - and it turns out to be really simple and functional, so I wanted to share :)