Java implements Windows system services __java

Source: Internet
Author: User
Tags thread class

One of the most immediate advantages of Windows system Services (NT services) versus ordinary applications is that the system can run directly after booting without the user logging on to the system. In fact, the system used as a server usually does not require a login system, which is not only convenient, but also improves the security of the system. However, normally, Windows system services are implemented using C or C + +, and sometimes, based on some considerations, we expect to use Java to implement system services that can be achieved with the help of open source Javaservice.

The following shows the implementation process.

The Java class that implements the NT service is written first, and the following example code achieves the purpose of implementing NT services through two classes. Class Testservice provides a way to control the start and stop of NT service, while the class service realizes the work that NT service really needs to complete. The complete code for class Testservice and class service is as follows:

Package Com.yanzhijun; Import Java.util.Calendar; public class Testservice {private static Thread thread=null; private static Service service = NULL;/** * Exit Service method (this method must have parameters String [] args * @param args */public static void StopService (string[] args) {System.out.println ("stop Service"); Service.setr Unflag (FALSE); /** * Start Service method (this method must have parameters String [] args) * @param args/public static void StartService (string[] args) {System.out.print ln ("Start service"); Generate Service Thread server = new services (); Thread=new Thread (service); try {///Set the service thread as a user thread to prevent the thread from exiting Thread.setdaemon (false) after the StartService method ends; if (!thread.isdaemon ()) {System.out.println (" Successfully set thread as user thread. "); } Start service thread Thread.Start (); The catch (SecurityException se) {System.out.println ("Thread type setting failed.") "); } } } Class Service implements Runnable {Private Boolean runflag = true;/** * Set service thread run flag value * @param runflag/Public Synchroni zed void Setrunflag (Boolean runflag) {this.runflag = Runflag;}/** * Get service thread Run flag value * @param void/private synchronized B Oolean Getrunflag () {return Runflag} @Override public void Run () {System.out.println ("service thread starts running"); while (Getrunflag ()) {Calendar cal = Ca Lendar.getinstance (); Long mis = Cal.gettimeinmillis (); System.out.println ("Current time:" + mis); try {thread.sleep (1000*10);} catch (Interruptedexception e) {e.printstacktrace ();}} SYSTEM.OUT.PRINTLN ("Service thread ends running"); } }

The method StartService in class Testservice is used to start the NT service, while the StopService method is used to stop the NT service. As you can see from the code, methods StartService and StopService actually implement the function of starting and terminating threads, and the thread here is the thread that implements the NT service. Here are two points to pay special attention to:

1. Method StartService and StopService all have parameters string[] args, when you install the NT service, you can specify the parameters that start or stop the service, which can be passed to the method string[by args] Startse Rvice and StopService. In this case, this argument was never made because the function of the demo was simpler.

2. Before starting a thread in the StartService method, it is necessary to set the thread as a user thread. The reason is that if the thread is a background thread, the JVM will automatically exit when the main program is finished, and the background thread will of course terminate, and if the main program ends with a user thread running, the JVM does not exit automatically, but waits until the user thread finishes. Therefore, to ensure that the NT service is running properly, this is also a special note.

The class service is the thread class that implements the NT service, the function that the NT service completes in the method run, in the example it only outputs the current time, in the actual application should be in the need to complete the more complex function in it. Method Setrunflag and Getrunflag are used respectively to set the flag that the thread is running and to get the flag value. The Setrunflag method needs to be called outside the class and notifies the thread whether it needs to continue execution by setting different parameters, and the Getrunflag method obtains the flag, which is invoked only in the loop of the method run, and is declared as a private method. In addition, the method Setrunflag and Getrunflag are set as synchronization methods because the thread-running flags are set and read in different threads.

After the code is written, execute the compilation process and, if necessary, package it into a jar file.

The next task is to use Javaservice to register NT services, Javaservice is an open source project with a project address of http:// Javaservice.objectweb.org, after opening the address, download the Javaservice package and place the extracted JavaService.exe in the directory where the package was compiled, or add JavaService.exe directory to the environment variable path Among

Javaservice provides a total of 8 parameters to choose from, where we only need to be concerned with the-install parameters for installing NT services and the-uninstall parameters for uninstalling NT services.

The use of the-install parameter to install NT services also requires some additional service-related parameters, with the following command format:

Javaservice-install service_name jvm_library [jvm_options]

-start Start_class [-method Start_method] [-params (start_parameters)]

[-stop Start_class [-method Stop_method] [-params (stop_parameters)]]

[-out Out_log_file] [-err Err_log_file]

[-current Current_dir]

[-path Extra_path]

[-depends Other_service]

[-auto |-manual]

[-shutdown seconds]

[-user user_name-password Password]

[-append |-overwrite]

[-startup seconds]

[-description Service_desc]

The function of the related parameters is described as follows:

Service_name:the name of the service.

Jvm_library:the location of the JVM DLL used to run the service.

Jvm_option:an option to use when starting the JVM, such as:

"-djava.class.path=c:/classes" or "-xmx128m".

Start_class:the class to load when starting the service.

Start_method:the the Start_class. Default:main

Start_parameters:parameter (s) to the Start_method.

Stop_class:the class to load when stopping the service.

Stop_method:the the Stop_class. Default:main

Stop_parameters:parameter (s) to the Stop_method.

out_log_file:a file to redirect System.out into. (Gets overwritten)

err_log_file:a file to redirect System.err into. (Gets overwritten)

Current_dir:the Current working directory for the service.

Relative paths is relative to this directory.

Extra_path:path additions, for native DLLs etc. (no spaces)

Other_service:single Service name dependency, must start a.

Auto/manual:startup Automatic (default) or manual mode.

Seconds:java Method Processing Time (Startup:sleep, shutdown:timeout).

User_name:user specified to execute the service (user@domain).

Password:password applicable if user specified to run the service.

Append/overwrite:log file output mode, append (default) or overwrite.

Service_desc:text describing installed service (quoted string, Max 1024).

To install the NT services we have written in Java earlier, you can do this by using the following command:

Javaservice.exe-install TJS "%java_home%/jre/bin/server/jvm.dll"-xmx128m-djava.class.path=%classpath%-start Com.yanzhijun.testservice-method startservice-stop com.yanzhijun.testservice-method stopservice-out "%CD%/out.log" -err "%cd%/err.log"-current "%cd%" –auto

"%" in the above command contains environment variables, where java_home is the installation directory of the JDK and Classpath is the lookup path for the class, which is consistent with the normal configuration of the JDK. The CD is the current directory.

After the service is successfully installed, you can start the service with the following command:

net start TJS

Because the auto parameter is specified when the service is installed, the service is set to start automatically, so the NT service will start after the machine restarts without using the above command.

If you need to stop the service, you can use the following command:

net stop TJS

This allows you to normally use the NT services written in Java, and if you do not need the service, you should uninstall the service and uninstall the service in a way that is much simpler than the installation, in the following format:

Javaservice-uninstall service_name

For example, to uninstall a service that has just been installed with the name TJs, you can execute the following command:

Javaservice-uninstall TJS

Note : The directory path stored by the NT service class generated by Java code cannot contain Chinese, or it will fail when you start the service.

Welcome to the Dream Break sober blog http://www.yanzhijun.com

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.