0

I'm trying to do a script with PowerShell and I need to execute some Java code in a loop. So I do :

while(something){
     java my_program
}

But my_program takes time and I would like to set a Timeout. How can I do this?

Martin Brandl
  • 56,134
  • 13
  • 133
  • 172
77140B
  • 41
  • 6

2 Answers2

0

You could try something like this:

while($something){
    $p = [diagnostics.process]::start("java my_program")
    if ( ! $p.WaitForExit(1000) ) 
    {
        $p.kill()
    }
}
Martin Brandl
  • 56,134
  • 13
  • 133
  • 172
  • Please explain your code. This is basically a code dump. – Rabbit Guy Aug 23 '16 at 12:48
  • @rabbitguy I thnk that this code doesn't need any explanations... However. It starts a the java application in a new process and assigns the process to `$p`. Then it waits 1000 miliseconds for the process to complete and kills it if it doesn't complete within this time... – Martin Brandl Aug 23 '16 at 12:52
  • Why $p = diagnostics.process]::start("C:/etc.../java.exe","package/my_programm" is not working ? – 77140B Aug 23 '16 at 14:12
0

I think this code will work fine for you, you can put while loop condition,

public class JavaTimeout {

    public void myMethod(){

        long startTime = System.currentTimeMillis(); // put the start time

        while((System.currentTimeMillis() - startTime ) < 5000) // if if 5 second end
        {
            // your method do something here 
        }
        System.out.println("5 sec end..."); // print the timeout

    } // end myMethod method

} // end JavaTimeout Class

I hope that helps..

MaJiD
  • 74
  • 1
  • 8