225

I've just inherited a java application that needs to be installed as a service on XP and vista. It's been about 8 years since I've used windows in any form and I've never had to create a service, let alone from something like a java app (I've got a jar for the app and a single dependency jar - log4j). What is the magic necessary to make this run as a service? I've got the source, so code modifications, though preferably avoided, are possible.

Jon Seigel
  • 11,819
  • 8
  • 53
  • 90
ideasculptor
  • 1,056
  • 3
  • 12
  • 19
  • An other suggestion http://stackoverflow.com/a/9262081/381897 – bhdrkn May 13 '14 at 10:37
  • 1
    Just for completeness: here http://serverfault.com/a/259195 it says the app needs to respond to Service Control Manager callbacks. Read this tutorial it uses Procrun http://ticklingmind.blogspot.com/2010/03/java-program-into-windows-service.html – Broken_Window Aug 18 '15 at 15:08
  • Other answer http://stackoverflow.com/questions/5953525/run-java-application-at-windows-startup/7009421 – Ravi Parekh Feb 13 '17 at 12:39

19 Answers19

104

Apache Commons Daemon is a good alternative. It has Procrun for windows services, and Jsvc for unix daemons. It uses less restrictive Apache license, and Apache Tomcat uses it as a part of itself to run on Windows and Linux! To get it work is a bit tricky, but there is an exhaustive article with working example.

Besides that, you may look at the bin\service.bat in Apache Tomcat to get an idea how to setup the service. In Tomcat they rename the Procrun binaries (prunsrv.exe -> tomcat6.exe, prunmgr.exe -> tomcat6w.exe).

Something I struggled with using Procrun, your start and stop methods must accept the parameters (String[] argv). For example "start(String[] argv)" and "stop(String[] argv)" would work, but "start()" and "stop()" would cause errors. If you can't modify those calls, consider making a bootstrapper class that can massage those calls to fit your needs.

Nate
  • 30,589
  • 12
  • 76
  • 201
mcdon
  • 4,648
  • 3
  • 34
  • 36
  • Using reflection, you could probably get around the issue you stated in your last paragraph. Also, apache commons daemon is the only wrapper i know of that has pre-built 64-bit binaries for free-use. – djangofan Nov 08 '11 at 23:41
  • 1
    You need a carriage return between each JVM Options. For instance if you have on the same line -Dopt1=a -Dopt2=b, it might not work. To fix it you need to write `--JvmOptions=-Dopt=a#-Dopt2=b`. I was running the command from a ant script and struggle for days because of that. Hope it helps. – Sydney Mar 14 '12 at 15:25
  • The article you talked about no long exists... Do you still have a way to get to it? I'm having trouble getting Apache Commons Daemon to do what I need. – 11101101b May 24 '12 at 14:26
  • 4
    @11101101b, apache seems to have attached the guts of the article to its [own wiki page](http://wiki.apache.org/commons/Daemon)... – Lucas Jun 28 '12 at 13:29
  • @community wiki, I used [Apache Commons Daemon](http://commons.apache.org/proper/commons-daemon/index.html) for 64-bit windows machine, it added the service successfully. while I am using the same processes for 32-bit windows 7 machine it fails to add service. – Shakthi Dec 29 '14 at 08:40
72

I've had some luck with the Java Service Wrapper

sblundy
  • 58,164
  • 22
  • 117
  • 120
  • 13
    Java Service Wrapper looks very useful. But I had a look at the feature list. You will just need to be aware that community version is not licensed for use on the server. – Brian Matthews Sep 16 '08 at 01:36
  • That could be a problem. It was a few years ago I used it. Guess they decided to charge. – sblundy Sep 16 '08 at 02:06
  • This wrapper is used by a lot of open source projects, include several on Jakarta Apache, such as ActiveMQ. – Todd Sep 16 '08 at 02:36
  • What I like about the wrapper is that it can be configured to restart the JVM if it locks up. – Andrew Swan Sep 16 '08 at 12:46
  • 7
    http://wrapper.tanukisoftware.org/doc/english/licenseCommunity.html Closed Source Use The GPL does not restrict private software from being developed for internal use which depends on software under the GPL as long as that software is never distributed without making the full source of the entire application available to all users. While we encourage corporate and government users to make use of either a Server or Development License Agreement, the Community License Agreement is acceptable as long as the application is for internal use or will be always be distributed along with its full src. – Vladimir Dec 30 '09 at 16:56
  • 1
    @Vladimir tanuki wrapper is no longer open sourced for 64bit arch – gerrytan Jul 03 '14 at 23:31
63

With Apache Commons Daemon you can now have a custom executable name and icon! You can also get a custom Windows tray monitor with your own name and icon!

I now have my service running with my own name and icon (prunsrv.exe), and the system tray monitor (prunmgr.exe) also has my own custom name and icon!

  1. Download the Apache Commons Daemon binaries (you will need prunsrv.exe and prunmgr.exe).

  2. Rename them to be MyServiceName.exe and MyServiceNamew.exe respectively.

  3. Download WinRun4J and use the RCEDIT.exe program that comes with it to modify the Apache executable to embed your own custom icon like this:

    > RCEDIT.exe /I MyServiceName.exe customIcon.ico
    > RCEDIT.exe /I MyServiceNamew.exe customTrayIcon.ico
    
  4. Now install your Windows service like this (see documentation for more details and options):

    > MyServiceName.exe //IS//MyServiceName \
      --Install="C:\path-to\MyServiceName.exe" \
      --Jvm=auto --Startup=auto --StartMode=jvm \
      --Classpath="C:\path-to\MyJarWithClassWithMainMethod.jar" \
      --StartClass=com.mydomain.MyClassWithMainMethod
    
  5. Now you have a Windows service of your Jar that will run with your own icon and name! You can also launch the monitor file and it will run in the system tray with your own icon and name.

    > MyServiceNamew.exe //MS//MyServiceName
    
Ulterior
  • 2,378
  • 3
  • 26
  • 56
11101101b
  • 7,351
  • 2
  • 37
  • 52
  • 1
    I did everything according to your How to, but it does not change the systray icon .. any idea why ? – outofBounds Jun 12 '12 at 13:12
  • Sorry @outofBounds, I didn't see your comment until just now. The RCEDIT.exe program is what modifies your service executable's icon. Make sure you have a valid .ico file with each size properly defined. You can see how to create a proper .ico file here: http://stackoverflow.com/questions/4354617/how-to-make-get-a-multi-size-ico-file – 11101101b Dec 03 '12 at 15:28
  • 2
    Just so you know, you cannot have spaces in the service name. – 11101101b Oct 02 '13 at 16:31
  • @11101101b, will this work in 32-bit windows 7 machine? – Shakthi Dec 29 '14 at 08:45
  • 1
    Yes @Shakthi it works fine on 32 and 64-bit Windows XP, 7, 8, 8.1, Server 2003, 2008, and 2012. – 11101101b Dec 30 '14 at 20:20
  • This may not be final answer but run below commands c:\Temp>prunsrv.exe //IS//VIJAY create service of name VIJAY c:\temp\prunmgr.exe //ES//VIJAY start UI to edit service VIJAY Its easy to edit paramaters from UI – Vijay Dec 16 '15 at 08:52
  • 1
    Yes, @Syamsoul Azrein, it works great on 10 and any server edition. – 11101101b Jan 21 '19 at 00:50
  • Thanks for pointing me in the right direction. Also see https://joerglenhard.wordpress.com/2012/05/29/build-windows-service-from-java-application-with-procrun/ for a more comprehensive example. – pm_ May 07 '20 at 14:57
31

A simple way is the NSSM Wrapper Wrapper (see my blog entry).

Matthieu
  • 2,529
  • 4
  • 49
  • 80
Giordano Maestro
  • 341
  • 1
  • 5
  • 9
  • 7
    NSSM ROCKS! I easy makes wrapper even from my java program. Easy, lightweight, works - 100kb of hapiness! Thank you! – cynepnaxa Mar 20 '14 at 10:11
  • 1
    Any example, how to use NSSM Wrapper to start java app (I'm using HelioSearch ) instance as a windows service in background on system start-up? – Krunal Jan 08 '15 at 12:21
  • @GiordanoMaestro your blog entry is not accessible anymore. Do you have another link? – Matthieu Mar 09 '15 at 19:39
  • 2
    Compared on Apache Commons Daemon, wrapper.tanukisoftware.org, & yajsw, NSSM was by far the quickest & easiest option for turning a simple java app into a windows service – Jeffrey Knight Mar 19 '16 at 23:06
  • I am trying to use NSSM to run my spring boot executable jar. I got this error, "Unexpected status SERVICE_PAUSED in response to START control." – Kiran Kumar Sep 04 '16 at 15:47
  • @java developer see this answer from "gcerkez" http://stackoverflow.com/questions/1617458/how-to-create-windows-service-from-java-jar – J.Z. Jan 13 '17 at 14:00
  • Had a .cmd file with java -jar myapp.jar which runs my java application. Installed it as a service practically within 3 mins. Such a breeze.. My only complain is with the name.. can you come up with a better name that does use the "S***" word ? – VenVig Jan 23 '19 at 16:55
  • @VenVig, Could you please tell me how did you run java -jar command as a windows service? Any help would be appreciated! – Nikhil Singh Bhadoriya Apr 10 '20 at 07:30
  • 1
    @NikhilSinghBhadoriya sorry, didn' notice this question till now. However if you happen to still need it, all I did was to have the java -jar command in a windows batch file and directed NSSM to run that batch file as a service. – VenVig Sep 25 '20 at 19:48
26

One more option is WinRun4J. This is a configurable java launcher that doubles as a windows service host (both 32 and 64 bit versions). It is open source and there are no restrictions on its use.

(full disclosure: I work on this project).

Peter Smith
  • 713
  • 6
  • 7
  • 3
    Thanks for this. I've tried YAJWS and first it scared me with 19mb download, and after I followed instructions it showed "error parsing command line". I've looked at PROCRUN and it's just too cumbersome for a quick setup. INSTSRV / SRVANY requires registry changes! Launch4J packs a JAR inside an EXE, so it complicates deployments. WinRun4J was a perfect fit. The only drawback is that it requires a special class for working as a service (instead of simply calling standard main class). But overall it's 99% perfect. – fernacolo May 16 '11 at 00:07
  • 2
    FYI, the latest version has a wrapper for a standard main class. – Peter Smith Sep 19 '11 at 14:59
  • Hi, Can you give any example that explains how to use this? I would like to use it to start HelioSearch instance as a background windows service on system startup. – Krunal Jan 08 '15 at 12:19
17

Yet another answer is Yet Another Java Service Wrapper, this seems like a good alternative to Java Service Wrapper as has better licensing. It is also intended to be easy to move from JSW to YAJSW. Certainly for me, brand new to windows servers and trying to get a Java app running as a service, it was very easy to use.

Some others I found, but didn't end up using:

  • Java Service Launcher I didn't use this because it looked more complicated to get working than YAJSW. I don't think this is a wrapper.
  • JSmooth Creating Window's services isn't its primary goal, but can be done. I didn't use this because there's been no activity since 2007.
atomicules
  • 2,065
  • 25
  • 24
  • +1 from me as this was the quickest solution for me "out of the box" and no modification of java app was required which is a definite plus. – Green Day Nov 07 '13 at 22:48
  • I found this very compelling comparison chart that compared YAJSW with a few other common service wrappers. http://yajsw.sourceforge.net/#mozTocId284533 – Green Jun 17 '14 at 18:15
7

If you use Gradle Build Tool you can try my windows-service-plugin, which facilitates using of Apache Commons Daemon Procrun.

To create a java windows service application with the plugin you need to go through several simple steps.

  1. Create a main service class with the appropriate method.

    public class MyService {
    
        public static void main(String[] args) {
            String command = "start";
            if (args.length > 0) {
                command = args[0];
            }
            if ("start".equals(command)) {
                // process service start function
            } else {
                // process service stop function
            }
        }
    
    }
    
  2. Include the plugin into your build.gradle file.

    buildscript {
      repositories {
        maven {
          url "https://plugins.gradle.org/m2/"
        }
      }
      dependencies {
        classpath "gradle.plugin.com.github.alexeylisyutenko:windows-service-plugin:1.1.0"
      }
    }
    
    apply plugin: "com.github.alexeylisyutenko.windows-service-plugin"
    

    The same script snippet for new, incubating, plugin mechanism introduced in Gradle 2.1:

    plugins {
      id "com.github.alexeylisyutenko.windows-service-plugin" version "1.1.0"
    }
    
  3. Configure the plugin.

    windowsService {
      architecture = 'amd64'
      displayName = 'TestService'
      description = 'Service generated with using gradle plugin'   
      startClass = 'MyService'
      startMethod = 'main'
      startParams = 'start'
      stopClass = 'MyService'
      stopMethod = 'main'
      stopParams = 'stop'
      startup = 'auto'
    }
    
  4. Run createWindowsService gradle task to create a windows service distribution.

That's all you need to do to create a simple windows service. The plugin will automatically download Apache Commons Daemon Procrun binaries, extract this binaries to the service distribution directory and create batch files for installation/uninstallation of the service.

In ${project.buildDir}/windows-service directory you will find service executables, batch scripts for installation/uninstallation of the service and all runtime libraries. To install the service run <project-name>-install.bat and if you want to uninstall the service run <project-name>-uninstall.bat. To start and stop the service use <project-name>w.exe executable.

Note that the method handling service start should create and start a separate thread to carry out the processing, and then return. The main method is called from different threads when you start and stop the service.

For more information, please read about the plugin and Apache Commons Daemon Procrun.

6

I think the Java Service Wrapper works well. Note that there are three ways to integrate your application. It sounds like option 1 will work best for you given that you don't want to change the code. The configuration file can get a little crazy, but just remember that (for option 1) the program you're starting and for which you'll be specifying arguments, is their helper program, which will then start your program. They have an example configuration file for this.

Ed Thomas
  • 1,143
  • 1
  • 12
  • 20
4

JavaService is LGPL. It is very easy and stable. Highly recommended.

NT_
  • 2,642
  • 21
  • 25
4

Use "winsw" which was written for Glassfish v3 but works well with Java programs in general.

Require .NET runtime installed.

emerino
  • 980
  • 10
  • 17
Thorbjørn Ravn Andersen
  • 68,906
  • 28
  • 171
  • 323
3

it's simple as you have to put shortcut in

Windows 7 C:\users\All Users\Start Menu\Programs\Startup(Admin) or User home directory(%userProfile%)

Windows 10 : In Run shell:startup

in it's property -> shortcut -> target - > java.exe -jar D:\..\runJar.jar

NOTE: This will run only after you login


With Admin Right

sc create serviceName binpath= "java.exe -jar D:\..\runJar.jar" Will create windows service

if you get timeout use cmd /c D:\JAVA7~1\jdk1.7.0_51\bin\java.exe -jar d:\jenkins\jenkins.war but even with this you'll get timeout but in background java.exe will be started. Check in task manager

NOTE: This will run at windows logon start-up(before sign-in, Based on service 'Startup Type')

Detailed explanation of creating windows service

Community
  • 1
  • 1
Ravi Parekh
  • 3,038
  • 8
  • 34
  • 47
3

A pretty good comparison of different solutions is available at : http://yajsw.sourceforge.net/#mozTocId284533

Personally like launch4j

pushNpop
  • 1,715
  • 2
  • 15
  • 17
3

With Java 8 we can handle this scenario without any external tools. javapackager tool coming with java 8 provides an option to create self contained application bundles:

-native type Generate self-contained application bundles (if possible). Use the -B option to provide arguments to the bundlers being used. If type is specified, then only a bundle of this type is created. If no type is specified, all is used.

The following values are valid for type:

-native type
Generate self-contained application bundles (if possible). Use the -B option to provide arguments to the bundlers being used. If type is specified, then only a bundle of this type is created. If no type is specified, all is used.

The following values are valid for type:

all: Runs all of the installers for the platform on which it is running, and creates a disk image for the application. This value is used if type is not specified.
installer: Runs all of the installers for the platform on which it is running.
image: Creates a disk image for the application. On OS X, the image is the .app file. On Linux, the image is the directory that gets installed.
dmg: Generates a DMG file for OS X.
pkg: Generates a .pkg package for OS X.
mac.appStore: Generates a package for the Mac App Store.
rpm: Generates an RPM package for Linux.
deb: Generates a Debian package for Linux.

In case of windows refer the following doc we can create msi or exe as needed.

exe: Generates a Windows .exe package.
msi: Generates a Windows Installer package.
Steephen
  • 11,597
  • 6
  • 29
  • 41
  • 7
    This answer does not address the question. The javapackager can not be used to create a windows service directly, but rather create a self contained executable that e.g. includes the jre and other resources. – tobias_ Nov 23 '17 at 09:11
2

I've used JavaService before with good success. It hasn't been updated in a couple of years, but was pretty rock solid back when I used it.

  • GForge has been discontinued – lww Jun 07 '20 at 13:05
  • Working links: http://www.multiplan.co.uk/software/javaservice/ (documentation) http://download.forge.ow2.org/javaservice/ (source and binaries) I inherited a project that uses JavaService. It meets our needs, even if it's a bit ancient by now. – Gary Sheppard Dec 09 '20 at 12:46
2

I didn't like the licensing for the Java Service Wrapper. I went with ActiveState Perl to write a service that does the work.

I thought about writing a service in C#, but my time constraints were too tight.

Hugh Buchanan
  • 1,619
  • 2
  • 12
  • 9
2

I always just use sc.exe (see http://support.microsoft.com/kb/251192). It should be installed on XP from SP1, and if it's not in your flavor of Vista, you can download load it with the Vista resource kit.

I haven't done anything too complicated with Java, but using either a fully qualified command line argument (x:\java.exe ....) or creating a script with Ant to include depencies and set parameters works fine for me.

Kevin
  • 61
  • 1
  • 6
  • 1
    That allows you to start something as a service, but in my understanding it would then be detached, i.e. you couldn't stop it via Services or restart automatically, etc. I could be completely wrong though - only just started looking into this. – atomicules Sep 02 '10 at 10:42
1

I am currently requiring this to run an Eclipse-based application but I need to set some variables first that is local to that application. sc.exe will only allow executables but not scripts so I turned to autoexnt.exe which is part of the Windows 2003 resource kit. It restricts the service to a single batch file but I only need one batch script to be converted into a service.

ciao!

1

Another good option is FireDaemon. It's used by some big shops like NASA, IBM, etc; see their web site for a full list.

Andrew Swan
  • 12,737
  • 19
  • 64
  • 97
-1

Exe4j is a very good option although it is not free. Check it out at Exe4j In the wizard to create the .exe file, you are give the option to create a service.

Ram
  • 799
  • 15
  • 32