Friday 8 August 2014

Timeouts on Windows Shell Commands

The common problem of using external apps through running by Windows Script Host Shell like: WshShell.RUN('ping microsoft.com',TRUE,TRUE) is that the code performing is stopps if the app malfunction and doesn't finish which causes freeze in NAV. The following example shows how to use defined timeout to prevent freezes while running any external apps or scripts by Windows Shell:

Instead of code:
WshShell.Run(Commandline,WindowStyle,WaitOnReturn);
use custom function:
ExecCommand(Commandline,Setup."Processing Timeout");

Function's signature:

PROCEDURE ExecCommand(CommandString : Text[1024];Timeout : BigInteger) : Boolean

VAR
      WshShell : Automation 'Windows Script Host Object Model'.WshShell;
      WshExec : Automation 'Windows Script Host Object Model'.WshExec;
      TimeStep : Integer;
      WindowStyle : Integer;
      ElapsedTime : Integer;
      WaitOnReturn : Boolean;
      ExecTimedOut : Boolean;

CODE:
CREATE(WshShell);
TimeStep := 1000;
WindowStyle := 0;
WaitOnReturn := FALSE;
WshExec := WshShell.Exec(CommandString);
WHILE (FORMAT(WshExec.Status) = '0') AND ((ElapsedTime <= Timeout) OR (Timeout = 0)) DO BEGIN
  SLEEP(TimeStep);
  ElapsedTime += TimeStep;
END;
ExecTimedOut := FORMAT(WshExec.Status) = '0';
IF ExecTimedOut THEN
  WshShell.Run(STRSUBSTNO('taskkill /PID %1',WshExec.ProcessID),WindowStyle,WaitOnReturn);
       
IF ExecTimedOut THEN BEGIN
  // Here logs can be created
END;
EXIT(NOT ExecTimedOut);

No comments:

Post a Comment