Java用JavaService实现Windows系统服务

本文介绍了如何利用JavaService库在Windows上创建系统服务。通过解析JavaService的命令行参数,详细阐述了安装、配置及管理服务的过程,并提供了具体的命令示例。

        java项目中需要用到系统启动后就自动执行某功能的需求,自然而然想到的是Windows服务(NT服务),虽然C或者C++也能实现它,但是这里用到了开源的JavaService来实现,其项目地址为:http://javaservice.objectweb.org,可以在上面下载JavaService.exe,也可以在CSDN下载:http://download.csdn.net/detail/sky1718/9487085

        下面开始实现NT服务。这里需要用到两个类,一个是控制NT服务启动和停止的类,另外一个是实现NT服务的线程类。如下:

public class TestService {
	private static Thread thread = null;
	private static Service service = null;
	
	public static void stopService(String[] args){
		service.setServiceStatu(false);
	}
	
	public static void startService(String[] args){
		service = new Service();
		thread = new Thread(service);
		try{
			// 将服务线程设定为用户线程
			thread.setDaemon(false);
			if(!thread.isDaemon()){
				System.out.println("[" + new Date() + "]成功设定为用户线程!");
			}
			thread.start();
		}catch(SecurityException e){
			e.printStackTrace();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public static void main(String [] args){
		startService(args);
	}
}
public class Service implements Runnable {

	private boolean serviceStatu = true;
	
	public synchronized void setServiceStatu(boolean serviceStatu){
		this.serviceStatu = serviceStatu;
	}
	
	private synchronized boolean getServiceStatu(){
		return serviceStatu;
	}
	
	@Override
	public void run() {
		try {
			while(getServiceStatu()){
				System.out.println("[" + new Date() + "]服务运行中...");
			}
		}catch (Exception e) {
			e.printStackTrace();
		}

	}
}

        这里有两个问题需要注意:

        1.方法StartService和StopService都拥有参数,在安装NT服务的时候,我们可以指定启动或停止服务的参数。

        2.在启动线程之前,我们必须将线程设定为用户线程,因为如果线程是一个后台线程,则当主程序结束后JVM会自动退出,后台线程也就终止执行,而如果主程序结束时还有用户线程在运行则JVM不会自动退出,而是要等到用户线程结束后才退出,所以要保证你的服务正常运行,这个需要特别注意。

        我们可以写一个main方法测试下服务是否可以正常运行。这里的setServiceStatu和getServiceStatu两个方法是用于设定线程是正在否运行的状态,setServiceStatu需要在类外被调用并通过设定不同的参数来通知线程是否继续执行,由于会有不同的线程对线程运行状态进行设定和读取,所以这里的方法被设定为同步方法。

        服务编写完成后,下面就可以用JavaService部署运行编译好的程序了,必要时还可以将程序打包成jar文件。

        将JavaService.exe置于编译之后的服务程序所在的目录中,或者将JavaService.exe所在目录添加到环境变量PATH中。

        JavaService提供了8个参数可供选择,这里使用-install参数安装NT服务时还需要提供与服务相关的其它一些参数,其命令格式如下:
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]


        相关参数的作用说明如下:

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 method to call in the start_class. default: main
 start_parameters: Parameter(s) to pass in to the start_method.
 stop_class:   The class to load when stopping the service.
 stop_method:   The method to call in the stop_class. default: main
 stop_parameters:      Parameter(s) to pass in 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 will be relative to this directory.
 extra_path:   Path additions, for native DLLs etc. (no spaces)
 other_service: Single service name dependency, must start first.
 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).


        下面的命令是我自己项目中安装NT服务:

JavaService.exe  -install  TestService   "%JAVA_HOME%"/jre/bin/server/jvm.dll    -Xmx128m   -Djava.class.path="%JAVA_HOME%"/lib/tools.jar;"%CD%"/lib/jtds-1.2.5.jar;"%CD%" -start com.azure.TestService  -method  startService  -stop  com.azure.TestService  -method stopService -out "%CD%"/log/log.log -err "%CD%"/log/error.log  -current  "%CD%"  -auto


        成功安装服务后就可以用以下命令对其进行卸载,启动和停止操作了。

        JavaService.exe -uninstall TestService

        net start TestService

        net stop TestService

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值