I am trying to stop Tomcat Service and a custom service (which i have created in windows) using JNA in my Java program. Sometimes Tomcat service takes longer time to stop.
W32Service service = null;
long startTime = System.currentTimeMillis();
boolean isStopped = false;
try
{
W32ServiceManager serviceManager = new W32ServiceManager();
serviceManager.open(Winsvc.SC_MANAGER_ALL_ACCESS);
service = serviceManager.openService(serviceName, Winsvc.SC_MANAGER_ALL_ACCESS);
//service.queryStatus().dwWaitHint = 60000;
synchronized (service) {
service.stopService();
}
service.close();
} catch (Exception ex)
{
System.out.println("Timeout happened.");
}finally{
if(null != service.getHandle()){
while(!isStopped){
if(service.queryStatus().dwCurrentState == Winsvc.SERVICE_STOPPED
|| System.currentTimeMillis()-startTime >= Constants.SERVICE_STOP_WAIT_TIME){
isStopped=true;
}
}
if(System.currentTimeMillis()-startTime >= Constants.SERVICE_STOP_WAIT_TIME){
System.out.println("Service Continuing.....");
throw new ServiceNotStoppedException("Service Not Stopped after 2 minutes");
}else{
System.out.println("Service Stopped");
isStopped=true;
}
}else{
System.out.println("Service Stopped.");
isStopped=true;
}
}
In the above code, i am catching a Runtime Exception thrown which give the below message.
java.lang.RuntimeException: Timeout waiting for service to change to a non-pending state.
at com.sun.jna.platform.win32.W32Service.waitForNonPendingState(W32Service.java:162)
at com.sun.jna.platform.win32.W32Service.stopService(W32Service.java:98)
at com.taskkill.sample.Sample.stopService(Sample.java:32)
at com.taskkill.sample.Sample.main(Sample.java:12)
I have checked previous threads on similar topic but couldn't find any resolution. It is waiting for a default time and throwing error. Is there any way we can extend this time dwWaithint? (I have tried //service.queryStatus().dwWaitHint = 60000;) but it doesn't work. Tomcat Service is eventually stopping/Hung while using this method. This works but is there a better way to handle the RunTimeException?
If i use command prompt process by the following code, it returns exit code "0" immediately, whereas the process is still stopping in the background.
String[] stopTomcat = { "sc", "stop", "Tomcat7" };
Process tomcatProcess = Runtime.getRuntime().exec(stopTomcat);