Run JAR as a Windows service

37,704

Solution 1

Write your own service from these samples:

Into onStart you have to do CreateProcess( "java", "-jar", "MyJar.jar" ), keep its PID

Into onStop you have to kill by the PID

Solution 2

Try this java launcher

http://winrun4j.sourceforge.net/

free and open source

start service example at the end of the page

Solution 3

You can use Java Service Wrapper

http://wrapper.tanukisoftware.com/doc/english/download.jsp

They not to distribute compiled x86_64 windows version of Comunity Edition but you can build it by yourself.

Share:
37,704
BTakacs
Author by

BTakacs

Updated on December 29, 2020

Comments

  • BTakacs
    BTakacs over 3 years

    I have a JAR file and I would like to register and run it as a Windows service. With a well-configured JAR and already registered JVM shutdown hooks it should not be a big work to do this.

    I already have a JAR with external lib dir, I can start it with java -jar My.jar and stop with Ctrl+C.

    I also checked JSL, JSmooth, and procrun from Apache with no working solution.

    I would need a working solution with a good tutorial.

    Update: I succeeded with both procrun (at last), and the manual .net service wrapper too... Here is the code for the procrun version of my install.bat:

    set PR_PATH=%CD%
    SET PR_SERVICE_NAME=MyService
    SET PR_JAR=MyService.jar
    SET START_CLASS=org.my.Main
    SET START_METHOD=main
    SET STOP_CLASS=java.lang.System
    SET STOP_METHOD=exit
    rem ; separated values
    SET STOP_PARAMS=0
    rem ; separated values
    SET JVM_OPTIONS=-Dapp.home=%PR_PATH%
    prunsrv.exe //IS//%PR_SERVICE_NAME% --Install="%PR_PATH%\prunsrv.exe" --Jvm=auto --Startup=auto --StartMode=jvm --StartClass=%START_CLASS% --StartMethod=%START_METHOD% --StopMode=jvm --StopClass=%STOP_CLASS% --StopMethod=%STOP_METHOD% ++StopParams=%STOP_PARAMS% --Classpath="%PR_PATH%\%PR_JAR%" --DisplayName="%PR_SERVICE_NAME%" ++JvmOptions=%JVM_OPTIONS%
    

    I presume to

    • run this from the same directory where the jar and prunsrv.exe is
    • the jar has its working MANIFEST.MF
    • and you have shutdown hooks registered into JVM (for example with context.registerShutdownHook() in Spring)...
    • not using relative paths for files outside the jar (for example log4j should be used with log4j.appender.X.File=${app.home}/logs/my.log or something alike)

    Thanks to the apache procrun team (http://commons.apache.org/proper/commons-daemon//procrun.html) and to marifnst (http://a089lp.wordpress.com/tag/procrun-tutorial/)

    Update 2: a new good tutorial with winsv: https://dzone.com/articles/spring-boot-as-a-windows-service-in-5-minutes

  • Prabhu Prabhakaran
    Prabhu Prabhakaran about 11 years
    Fine and Easy one To Use
  • BTakacs
    BTakacs about 11 years
    Thanks. It's working with Process.Start( "java", "-jar MyJar.jar" )
  • firephil
    firephil over 10 years
    that's a cool utiity thanks