Wait for JSch command to execute instead of hard coding a fixed time to wait for

梦想与她 提交于 2019-12-06 12:54:37

问题


Channel channel=session.openChannel("shell");
channel.setInputStream(System.in);
channel.setOutputStream(System.out);
channel.connect();
while (channel.getExitStatus() == -1){
   try{Thread.sleep(1000);}catch(Exception e){System.out.println(e);}
}   
channel.disconnect();

In the code above we add line Thread.sleep(1000); to give the system enough time, to execute the command. However when I change the time gap from 1000 ms to 200 ms, the command doesn't execute.

Also in some slow servers, the command may not execute for the specified time gap of 1000 ms too. Is there any other dynamic way to wait for the command to execute completely before the next starts executing instead of hard coding the value, especially required while automating?


回答1:


You have to loop reading chunks of the response until channel.isClosed() returns true.

At that point you can call channel.getExitStatus() to get the process exit code and then close the channel.

If you don't want to burn CPU cycles while looping to read the response bytes, put a Thread.sleep(100) between each read.



来源:https://stackoverflow.com/questions/22734134/wait-for-jsch-command-to-execute-instead-of-hard-coding-a-fixed-time-to-wait-for

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!