Start windows service in java

start windows service from java

You can formulate a Command Prompt script to start, stop, and check status on a service using a String Array:

// start service String[] script = ; // stop service String[] script = ; // check whether service is running or not String[] script = ; 

Execute scripts using the following:

Process process = Runtime.getRuntime().exec(script); 

Solution 2

import java.io.*; import java.util.*; public class ServiceStartStop < public static void main(String args[]) < String[] command = ; try < Process process = new ProcessBuilder(command).start(); InputStream inputStream = process.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String line; while ((line = bufferedReader.readLine()) != null) < System.out.println(line); >> catch(Exception ex) < System.out.println("Exception : "+ex); >> > 

It worked fine . instead of «sc» use «net» command.

Solution 3

You can execute system commands from java using the exec () command — A simple tutorial on the same can be found here — http://www.java-samples.com/showtutorial.php?tutorialid=8

Now you can use the system commands to start / stop windows services — A sample of the same can be found here

I am not very sure about monitoring the status , so can’t be of much help in that regards

Источник

Making a Java windows service in 10 minutes

A problem sometimes encountered by a Java programmer, is to make your Java program into a Windows Service. This is may be a bump in your project, particularly if you don’t know anything about windows services, or much about windows for that matter.

The demo created a running, working, Windows service server using 14 lines of Java code, and some maven configuration.

Before starting on the demo, a few words on what windows services are (from a GNU/linux/UNIX perspective):

  • Windows services are the “daemons” of the windows world
  • Windows services are normally started when the windows system starts, and stopped when the windows system shuts down
  • Windows services can be stopped and started by administrator users, both using a GUI and using command line commands
  • Windows services can be configured to run with a particular user, restricting what the service can do (default is the local user “Local System”)

To create the installer the demo use a maven plugin called maven-windows-service-installer-plugin. The maven plugin in turn relies on izpack for the installer and uses the apache commons daemon to execute the Java program.

The Java program turned into a windows service during the demo, is the Wiser test SMTP server. Wiser was picked, because:

  1. It has an appropriate API
  2. An SMTP service is easy to demonstrate, and it is something other than yet another HTTP service

Since the demo might be hard to follow (a lot of information in 10 minutes), this blog post describes all steps of the demo (note: the complete code can be found on github at https://github.com/sbang/ansmtpserver ).

Required software to retrace the demo:

  • Apache maven (any maven 2 or 3 will do)
  • A Java SDK (I’m using the newest Java 1.8, but any Java SDK 1.7 will probably do)
  • An eclipse IDE (I’m using Eclipse Neon, but any recent eclipse will probably do)
  • A telnet command line application (since this is for windows, just use Windows cygwin bash with the inetutils package, just run the installer and include inetutils)

To retrace the demo, do the following operations:

  1. Start eclipse and open the Workspace “C:\workspace”
  2. Right click the package explorer and select New->Other…
  3. In the “New” dialog box:
    1. Select Maven->Maven Project
    2. Click the “Next>” button
    3. Checkmark the checkbox “Create a simple project (skip archetype selection)” at the to of the dialogbox
    4. Click the “Next>” button
    5. In the “Group id” text box, type
    package ansmtpserver; import org.subethamail.wiser.Wiser; import com.alexkasko.installer.DaemonLauncher; public class AnSmtpServer implements DaemonLauncher < private Wiser server; public AnSmtpServer() < super(); server = new Wiser(); server.setHostname("javazone"); server.setPort(2200); >public void startDaemon() < server.start(); >public void stopDaemon() < server.stop(); >>
    1. Add a Wiser field
    2. In the constructor, create an Wiser instance, set the host name, and the port number
    3. In the startDaemon() method start the Wiser server
    4. In the stopDaemon() method stop the Wiser server
    org.slf4j.simpleLogger.defaultLogLevel=debug
       com.alexkasko.installer maven-windows-service-installer-plugin 1.0.6  com.alexkasko.installer windows-service-installer-common 1.0.6   true   build-installer package installer      
    cd c:\windows\ansmtpserver mvn clean install
    Trying 127.0.0.1. telnet: Unable to connect to remote host: Connection refused

    since nothing is listening to port 2200

  4. Click the installer all the way to the end, using defaults for everything
  5. Open the windows services window and there will be a new windows service “ansmtpservice” shown as “Running”Windows services with the ansmtpserver shown
  6. Try the “telnet localhost 2200” command again, and this time there will be a response, and it will be possible to talk SMTP over the connectiontelnet_session
  7. Stop the “ansmtpservice” service and the telnet connection will be disconnected

Thus ends the installer part.

Some simple improvements to this installer are possible:

    Better descrption for the service in “Windows Services”

      Just add the following to the setting of the maven-windows-service-installer-plugin:
    AnSmtpServer An SMTP server This service responds to incoming STMP connections on port 2200.
    $APPLICATIONS_DEFAULT_ROOT\ansmtpserver
     org.codehaus.mojo build-helper-maven-plugin 1.10  attach-artifacts package attach-artifact    target/$-$-installer.zip zip installer        

    A windows-service-installer that contains the above improvements and more, is this installer for Apache Jena Fuseki.

    Источник

    Java application as Windows Service

    In this blog post, I show you how to install a Java application with WinSW as a Windows service. WinSW is an executable binary, which can be used to wrap and manage any custom process as a Windows service.

    Demo

    First, we need a demo application. I use a simple Quarkus application for this purpose. You can install any Java application as a service. Usually, you install applications that run forever like an HTTP server in this case.

    To bootstrap a Quarkus application run this command

    mvn io.quarkus:quarkus-maven-plugin:2.5.1.Final:create -DprojectGroupId=com.testlab -DprojectArtifactId=testservice -DclassName="com.testlab.testservice.GreetingResource" -Dpath="/hello" cd testservice 

    We use the application as is with just a small change. I want to create a fat jar. A jar with all dependent libraries included.
    You can package your application in any way you want. In this case, I prefer the fat jar installation because I only have to copy one file.

    Open src\main\resources\application.properties and insert the following property

    quarkus.package.type=uber-jar 

    Now you can package the application with .\mvnw.cmd package . You find the jar in the target folder: testservice-1.0.0-SNAPSHOT-runner.jar

    Preparation

    You can proceed in different ways. I usually create a new folder where I copy all the files into it that are needed to run the application as a service. Copy the jar from the target folder into this directory.

    Java

    Next, I download the Java Runtime and also copy it into this folder. This is optional. Your service can access a globally installed Java. But I like to have everything contained in one folder and don’t have to worry about somebody updating or removing the globally installed Java.

    I usually download Java from Adoptium. On the release page, you find the ZIP file with the JDK for Windows.

    Download the ZIP file and unzip it into the install folder. I unzip it into the java subfolder, so the java.exe is accessible with this path java\bin\java.exe

    WinSW

    Open the release page of the WinSW project and download the executable suitable for your platform.
    https://github.com/winsw/winsw/releases

    For this demo installation, I download WinSW.NET461.exe . WinSW runs on Windows with .NET Framework 2.0, 4.0 or 4.6.1. If you need to install the service on a Windows without .NET framework, download the core variant WinSW-x64.exe for 64-bit or WinSW-x86.exe` for 32-bit systems.

    Copy the executable also into the folder where your jar resided. Rename the WinSW executable to any name you like. For this example, I rename it to testservice.exe . Create an XML with the same base name: testservice.xml . Make sure that the exe and XML file are located in the same folder.

    Open the XML file and paste the following code into it.

    service> id>testserviceid> name>Test Servicename> description>This is a test service.description> executable>"%BASE%\java\bin\java"executable> arguments>-jar "%BASE%\testservice-1.0.0-SNAPSHOT-runner.jar"arguments> logmode>rotatelogmode> stopparentprocessfirst>truestopparentprocessfirst> service> 

    Check the executables path and arguments. %BASE% is an environment variable that points to the directory where the WinSW executable is located. If you want to start the application with a Java that is on the %PATH% , just use java .

    Relevant here is . This tells WinSW to shutdown the parent process first. In our case this is useful because the main process opens a console ( java ), which can respond to Ctrl+C and will gracefully shutdown the child process (the Java application).

    Check out this wiki page to learn more about all the supported options:
    https://github.com/winsw/winsw/blob/master/doc/xmlConfigFile.md

    Directory structure

    The directory structure of my install folder.

    testservice.exe testservice.xml testservice-1.0.0-SNAPSHOT-runner.jar java bin java.exe . conf legal lib . 

    Installation

    With everything in place you install the Windows service with this command

    The WinSW command supports the following options:

    • install : Install the service
    • uninstall : Uninstall the service
    • start : Start the installed service
    • stop : Stop the service
    • restart : Restart the service
    • status : Show the current service status (NonExistent, Started, Stopped)

    The service by default is installed with start mode Automatic . That means Windows starts the service when it boots up. You can change that with the configuration in the XML file.

    To test the installation, open http://localhost:8080 in a browser. You should see the default start page of Quarkus. To test if the graceful shutdown works, stop the service

    Open the file testservice.out.log .

    2020-05-06 05:30:52,501 INFO [io.quarkus] (main) Profile prod activated. 2020-05-06 05:30:52,501 INFO [io.quarkus] (main) Installed features: [cdi, resteasy] 2020-05-06 05:30:54,801 INFO [io.quarkus] (main) testservice stopped in 0.032s 

    We see that the application shutdown gracefully because of the testservice stopped log entry.

    Note that WinSW creates by default three logs files:

    • .out.log : Console output from the application ( System.out.println )
    • .err.log : Error output from the application ( System.err.println )
    • .wrapper.log : Log output from WinSW itself

    That concludes this tutorial about installing any Java applications as Windows Service. Optionally you could try and create a native image of your application with GraalVM. The service installation does not change a lot. You don’t need the JRE anymore and have to change accordingly.

    Источник

    Читайте также:  Dm surf server css v34
Оцените статью