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.
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.
I've had some luck with the Java Service Wrapper
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!
Download the Apache Commons Daemon binaries (you will need prunsrv.exe and prunmgr.exe).
Rename them to be MyServiceName.exe and MyServiceNamew.exe respectively.
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
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
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
A simple way is the NSSM Wrapper Wrapper (see my blog entry).
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).
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.
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.
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
}
}
}
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"
}
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'
}
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.
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.
Use "winsw" which was written for Glassfish v3 but works well with Java programs in general.
Require .NET runtime installed.
JavaService is LGPL. It is very easy and stable. Highly recommended.
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.
A pretty good comparison of different solutions is available at :
http://yajsw.sourceforge.net/#mozTocId284533
Personally like launch4j
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.
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.
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.
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
Another good option is FireDaemon. It's used by some big shops like NASA, IBM, etc; see their web site for a full list.
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!
I have been using jar2exe for last few years to run our Java applications as service on Windows. It provides an option to create an exe file which can be installed as Windows service.
It's possible to implement a Windows service in 100% Java code by combining the use of Foreign Memory and Linker API (previewing from JDK16 upwards) with OpenJDK jextract project to handle the Windows Service callbacks, and then use jpackage to produce a Windows EXE which can then be registered as a Windows Service.
See this example which outlines the work needed to implement a Windows service. All Windows service EXE must provide callbacks for the main entrypoint ServiceMain and Service Control Handler, and use API calls StartServiceCtrlDispatcherW, RegisterServiceCtrlHandlerExW and SetServiceStatus in Advapi.DLL.
The flow of above callbacks in Java with Foreign Memory structures are:
main()
Must register ServiceMain using StartServiceCtrlDispatcherW
Above call blocks until ServiceMain exits
void ServiceMain(int dwNumServicesArgs, MemoryAddress lpServiceArgVectors)
Must register SvcCtrlHandler using RegisterServiceCtrlHandlerExW
Use SetServiceStatus(SERVICE_START_PENDING)
Initialise app
Use SetServiceStatus(SERVICE_RUNNING)
wait for app shutdown notification
Use SetServiceStatus(SERVICE_STOPPED)
int SvcCtrlHandler(int dwControl, int dwEventType, MemoryAddress lpEventData, MemoryAddress lpContext)
Must respond to service control events and report back using SetServiceStatus
On receiving SERVICE_CONTROL_STOP reports SetServiceStatus(SERVICE_STOP_PENDING)
then set app shutdown notification
Once finished the Java application, jpackage can create runtime+EXE which can then be installed and registered as a Windows Service. Run as Adminstrator (spaces after = are important):
sc create YourJavaServiceName type= own binpath= "c:\Program Files\Your Release Dir\yourjavaservice.exe"
Related
Situation:
I have installed Jasper Reports Library (V6.5.1) on my local Linux server which generates PDF reports (Data is dumped in a temp Oracle DB table for the reporting engine).
It then serves this PDF back to the website from which I kick off the process.
Goal:
Install Jmeter to analyse performance / possible bottlenecks of "Jasper Reports Library" (aka Report Generation) on my local linux server (I cannot access this server via GUI, only shell).
I understand I have to connect my local Windows 10 machine (running same Jmeter 4.0) with this local server. On the server I have to start Jmeter 4.0 Server (via jmeter-server command) however I get an error and am stuck (have not found anything online or even people with the same goal unfortunately...)
Steps I have taken:
Download latest (4.0) bin from here
Extracted on local linux server in /opt/dlins/apache-jmeter-4.0bin
Trying to start server with /usr/lib/jvm/jdk1.8.0_102/bin/java jmeter-server (the default java version is 6 so through this I can run this app with java 8) - Instructions found here
-> Getting error: "Error: Could not find or load main class jmeter-server"
Any help regarding above or even any other tool you may use are appreciated (Maybe there is a preferable way to test performance for the above scenario)
There are 2 aspects related to your issue and screenshot:
1) Using java 8 instead of 6 - This can be done in several ways, depending on your needs and restrictions, such as the need to have Java 6 globally available for other applications and using 8 just to run JMeter, or just replacing 6 with 8 entirely. For the sake of brevity, I'll assume the first scenario, but there's documentation available for both and Dmitri T has partially explained it already.
Anyway, the same JMeter doc link you used, describes (just scroll down a few times) how to create a setenv.sh script in the bin directory and configure JAVA_HOME or JRE_HOME depending on your needs.
To set those variables permanently, you can place them in a file called setenv.sh in the bin directory. This file will be sourced when running JMeter by calling the jmeter script.
You seem to be wanting a JDK, so create the script and add inside JAVA_HOME=/usr/lib/jvm/jdk1.8.0_102, save and exit.
2) Running JMeter - To clarify a minor confusion, java MyCompiledClass instructs java to load and execute the "program" defined in MyCompiledClass, which is not what you want to do, because jmeter-server is a shell script. If you open it, you'll see that it calls the jmeter shell script which will do some configuration, end eventually call (in short) java -jar ApacheJMeter.jar with some arguments and options.
So, to run JMeter make sure your scripts are executable with chmod, and simply run from command line ./jmeter-server. From the same link:
Un*x script files; should work on most Linux/Unix systems:
jmeter - run JMeter (in GUI mode by default). Defines some JVM settings which may not work for all JVMs.
jmeter-server - start JMeter in server mode (calls jmeter script with appropriate parameters)
jmeter.sh - very basic JMeter script (You may need to adapt JVM options like memory settings).
mirror-server.sh - runs the JMeter Mirror Server in non-GUI mode
shutdown.sh - Run the Shutdown client to stop a non-GUI instance gracefully
stoptest.sh - Run the Shutdown client to stop a non-GUI instance abruptly
Amend your PATH environment variable so Java 8 bin would be before Java 6 bin like:
PATH=/usr/lib/jvm/jdk1.8.0_102/bin:$PATH && export PATH
Once done you should be able to just launch the jmeter-server script like
pushd /opt/dlins/apache-jmeter-4.0bin/bin && ./jmeter-server
More information:
Remote Testing
JMeter Distributed Testing Step-by-step
How to Get Started With JMeter: Part 1 - Installation & Test Plans
I am trying to run Tomcat 7 as a Windows Service (XP and Windows 7).
I see places to set the -Xmx and -Xms jvm args in catalina.bat, but I'm not sure how to do it when using $CATALINA_HOME/bin/service.bat install service-name. I looked around but the best I could find was that I needed to update windows registry key, though I'm not sure which one to edit.
I'm hoping there's an easier way, is there?
Update: I'm not using the windows installer mainly because I'm running multiple instances of tomcat on the same machine but with different ports (for reasons I'd rather not go into here). If I can use the installer with multiple instances using different ports, then I'd like to know how, but regardless, is it possible to do increase the memory on a tomcat windows service without the UI tools that come with the installer?
Assuming that you've downloaded and installed Tomcat as Windows Service Installer exe file from the Tomcat homepage, then check the Apache feather icon in the systray (or when absent, run Monitor Tomcat from the start menu). Doubleclick the feather icon and go to the Java tab. There you can configure the memory.
Restart the service to let the changes take effect.
The answer to my own question is, I think, to use tomcat7.exe:
cd $CATALINA_HOME
.\bin\service.bat install tomcat
.\bin\tomcat7.exe //US//tomcat7 --JvmMs=512 --JvmMx=1024 --JvmSs=1024
Also, you can launch the UI tool mentioned by BalusC without the system tray or using the installer with tomcat7w.exe
.\bin\tomcat7w.exe //ES//tomcat
An additional note to this:
Setting the --JvmXX parameters (through the UI tool or the command line) may not be enough. You may also need to specify the JVM memory values explicitly. From the command line it may look like this:
bin\tomcat7w.exe //US//tomcat7 --JavaOptions=-Xmx=1024;-Xms=512;..
Be careful not to override the other JavaOption values. You can try updating bin\service.bat or use the UI tool and append the java options (separate each value with a new line).
//ES/tomcat -> This may not work if you have changed the service name during the installation.
Either run the command without any service name
.\bin\tomcat7w.exe //ES
or with exact service name
.\bin\tomcat7w.exe //ES/YourServiceName
According to catalina.sh customizations should always go into your own setenv.sh (or setenv.bat respectively) eg:
CATALINA_OPTS='-Xms512m -Xmx1024m'
My guess is that setenv.bat will also be called when starting a service.I might be wrong, though, since I'm not a windows user.
If you are running a custom named service, you should see two executables in your Tomcat/bin directory
In my case with Tomcat 8
08/14/2019 10:24 PM 116,648 Tomcat-Custom.exe
08/14/2019 10:24 PM 119,720 Tomcat-Customw.exe
2 File(s) 236,368 bytes
Running the "w" terminated executable will let you configure Xmx in the Java tab
For Tomcat 7 to increase memory :
Identify your service name, you will find it in the service properties, under the "Path to executable" at the end of the line
For me it is //RS//Tomcat70 so the name is Tomcat70
Then write as administrator :
tomcat7.exe //US//Tomcat70 --JvmOptions=-Xmx1024M
I have an executable JAR file. Is it possible to create a Windows service of that JAR? Actually, I just want to run that on startup, but I don't want to place that JAR file in my startup folder, neither in the registry.
The easiest solution I found for this so far is the Non-Sucking Service Manager
Usage would be
nssm install <servicename> "C:\Program Files\Java\jre7\java.exe" "-jar <path-to-jar-file>"
Use nssm.exe but remember to set the AppDirectory or any required libraries or resources will not be accessible. By default nssm set the current working directory to the that of the application, java.exe, not the jar.
So do this to create a batch script:
pushd <path-to-jar>
nssm.exe install "<service-name>" "<path-to-java.exe>" "-jar <name-of-jar>"
nssm.exe set "<service-name>" AppDirectory "<path-to-jar>"
This should fix the service paused issue.
I've been experimenting with Apache Commons Daemon. It's supports windows (Procrun) and unix (Jsvc). Advanced Installer has a Java Service tutorial with an example project to download. If you get their javaservice.jar running as a windows service you can test it by using "telnet 4444". I used their example because my focus was on getting a java windows service running, not writing java.
Tanuki changed license of jsw some time ago, if I was to begin a project, I would use Yet Another Java Service Wrapper, http://yajsw.sourceforge.net/ that is more or less an open source implementation that mimics JWS, and then builds on it and improves it even further.
EDIT: I have been using YAJSW for several years on several platorms (Windows, several linuxes...) and it is great, development is ongoing.
With procrun you need to copy prunsrv to the application directory (download), and create an install.bat like this:
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)
Check the procrun manual and this tutorial for more information.
Another option is winsw: https://github.com/kohsuke/winsw/
Configure an xml file to specify the service name, what to execute, any arguments etc. And use the exe to install. Example xml: https://github.com/kohsuke/winsw/tree/master/examples
I prefer this to nssm, because it is one lightweight exe; and the config xml is easy to share/commit to source code.
PS the service is installed by running your-service.exe install
[2020 Update]
Actually, after spending some times trying the different option provided here which are quite old, I found that the easiest way to do it was to use a small paid tool built for that purpose : FireDaemon Pro. I was trying to run Selenium standalone server as a service and none of the free option worked instantly.
The tool is quite cheap (50 USD one-time-licence, 30 days trial) and it took me 5 minutes to set up the server service instead of a half a day of reading/troubleshooting. So far, it works like a charm.
I have absolutely no link with FusionPro, this is a pure disinterested advice, but feel free to delete if it violates forum rules.
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.
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.
I've had some luck with the Java Service Wrapper
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!
Download the Apache Commons Daemon binaries (you will need prunsrv.exe and prunmgr.exe).
Rename them to be MyServiceName.exe and MyServiceNamew.exe respectively.
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
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
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
A simple way is the NSSM Wrapper Wrapper (see my blog entry).
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).
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.
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.
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
}
}
}
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"
}
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'
}
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.
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.
Use "winsw" which was written for Glassfish v3 but works well with Java programs in general.
Require .NET runtime installed.
JavaService is LGPL. It is very easy and stable. Highly recommended.
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.
A pretty good comparison of different solutions is available at :
http://yajsw.sourceforge.net/#mozTocId284533
Personally like launch4j
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.
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.
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.
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
Another good option is FireDaemon. It's used by some big shops like NASA, IBM, etc; see their web site for a full list.
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!
I have been using jar2exe for last few years to run our Java applications as service on Windows. It provides an option to create an exe file which can be installed as Windows service.
It's possible to implement a Windows service in 100% Java code by combining the use of Foreign Memory and Linker API (previewing from JDK16 upwards) with OpenJDK jextract project to handle the Windows Service callbacks, and then use jpackage to produce a Windows EXE which can then be registered as a Windows Service.
See this example which outlines the work needed to implement a Windows service. All Windows service EXE must provide callbacks for the main entrypoint ServiceMain and Service Control Handler, and use API calls StartServiceCtrlDispatcherW, RegisterServiceCtrlHandlerExW and SetServiceStatus in Advapi.DLL.
The flow of above callbacks in Java with Foreign Memory structures are:
main()
Must register ServiceMain using StartServiceCtrlDispatcherW
Above call blocks until ServiceMain exits
void ServiceMain(int dwNumServicesArgs, MemoryAddress lpServiceArgVectors)
Must register SvcCtrlHandler using RegisterServiceCtrlHandlerExW
Use SetServiceStatus(SERVICE_START_PENDING)
Initialise app
Use SetServiceStatus(SERVICE_RUNNING)
wait for app shutdown notification
Use SetServiceStatus(SERVICE_STOPPED)
int SvcCtrlHandler(int dwControl, int dwEventType, MemoryAddress lpEventData, MemoryAddress lpContext)
Must respond to service control events and report back using SetServiceStatus
On receiving SERVICE_CONTROL_STOP reports SetServiceStatus(SERVICE_STOP_PENDING)
then set app shutdown notification
Once finished the Java application, jpackage can create runtime+EXE which can then be installed and registered as a Windows Service. Run as Adminstrator (spaces after = are important):
sc create YourJavaServiceName type= own binpath= "c:\Program Files\Your Release Dir\yourjavaservice.exe"
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.
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.
I've had some luck with the Java Service Wrapper
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!
Download the Apache Commons Daemon binaries (you will need prunsrv.exe and prunmgr.exe).
Rename them to be MyServiceName.exe and MyServiceNamew.exe respectively.
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
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
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
A simple way is the NSSM Wrapper Wrapper (see my blog entry).
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).
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.
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.
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
}
}
}
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"
}
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'
}
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.
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.
Use "winsw" which was written for Glassfish v3 but works well with Java programs in general.
Require .NET runtime installed.
JavaService is LGPL. It is very easy and stable. Highly recommended.
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.
A pretty good comparison of different solutions is available at :
http://yajsw.sourceforge.net/#mozTocId284533
Personally like launch4j
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.
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.
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.
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
Another good option is FireDaemon. It's used by some big shops like NASA, IBM, etc; see their web site for a full list.
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!
I have been using jar2exe for last few years to run our Java applications as service on Windows. It provides an option to create an exe file which can be installed as Windows service.
It's possible to implement a Windows service in 100% Java code by combining the use of Foreign Memory and Linker API (previewing from JDK16 upwards) with OpenJDK jextract project to handle the Windows Service callbacks, and then use jpackage to produce a Windows EXE which can then be registered as a Windows Service.
See this example which outlines the work needed to implement a Windows service. All Windows service EXE must provide callbacks for the main entrypoint ServiceMain and Service Control Handler, and use API calls StartServiceCtrlDispatcherW, RegisterServiceCtrlHandlerExW and SetServiceStatus in Advapi.DLL.
The flow of above callbacks in Java with Foreign Memory structures are:
main()
Must register ServiceMain using StartServiceCtrlDispatcherW
Above call blocks until ServiceMain exits
void ServiceMain(int dwNumServicesArgs, MemoryAddress lpServiceArgVectors)
Must register SvcCtrlHandler using RegisterServiceCtrlHandlerExW
Use SetServiceStatus(SERVICE_START_PENDING)
Initialise app
Use SetServiceStatus(SERVICE_RUNNING)
wait for app shutdown notification
Use SetServiceStatus(SERVICE_STOPPED)
int SvcCtrlHandler(int dwControl, int dwEventType, MemoryAddress lpEventData, MemoryAddress lpContext)
Must respond to service control events and report back using SetServiceStatus
On receiving SERVICE_CONTROL_STOP reports SetServiceStatus(SERVICE_STOP_PENDING)
then set app shutdown notification
Once finished the Java application, jpackage can create runtime+EXE which can then be installed and registered as a Windows Service. Run as Adminstrator (spaces after = are important):
sc create YourJavaServiceName type= own binpath= "c:\Program Files\Your Release Dir\yourjavaservice.exe"