Running Java jars as windows service

Jay picture Jay · Dec 8, 2017 · Viewed 9.4k times · Source

I have an executable jar and I was trying to create a Windows Service using sc.exe. I used the below code for creating service:

sc create "TestService" binPath= "C:\Program Files\Java\jdk1.6.0_03\jre\bin\java.exe -jar C:\abc\MainClass.jar"

The service got created but when I was trying to start the service I got the below error:

Error 1053: The service did not respond to the start or control request in a timely fashion.

Later I tried to use Java Service Wrapper (Community Edition), the service starts for some time but is getting stopped everytime. The wrapper log tells something like:

Advice:
The Wrapper consists of a native component as well as a set of classes
which run within the JVM that it launches.  The Java component of the
Wrapper must be initialized promptly after the JVM is launched or the
Wrapper will timeout, as just happened.  Most likely the main class
specified in the Wrapper configuration file is not correctly initializing
the Wrapper classes:
com.MainClass
While it is possible to do so manually, the Wrapper ships with helper
classes to make this initialization processes automatic.
Please review the integration section of the Wrapper's documentation
for the various methods which can be employed to launch an application
within the Wrapper

Could anyone please tell me how can I run jar as a Windows Service without using external software as I can't use any third party app on Client's prod env.

If not what other configs I need to do in Java Service Wrapper to make the service start.

I tried to find some info related to this on stackoverflow but I did not get anything thing. If any one has anything on stackoverflow please feel free to put this in comment.

Answer

Walter picture Walter · Dec 8, 2017

I have used this approach before in a productive environment, so I can assure you it is safe to use.

The Jar-File is wrapped in an exe and then it is added to the windows service scheduler (or however you want to call this). If you have a maven project this is also really easy to accomplish.

https://dzone.com/articles/installing-a-java-application-as-a-windows-service

Edit: you said you can’t use external software. With this approach everything that is needed is packed in the exe file. Including a JRE, I hope that that is allowed by your client’s policy.