把java安装为服务

将java安装为服务,强烈推荐common daemon:

http://commons.apache.org/proper/commons-daemon/procrun.html

apache上的多个java项目都使用这个安装为windows服务。

用法很简单:

java类中的main函数中使用start和stop来做为启动和停止指令:

public static void main(String[] args) {
		System.out.println("start Pdf2Swf Service main with args:" + args);

		String mode = "start";
		if (args != null && args.length > 0) {
			mode = args[0];
		}
		if ("start".equals(mode)) {
			// 启动主线程
			Pdf2SwfService pdf2SwfService = new Pdf2SwfService();
			pdf2SwfService.run();
			Pdf2SwfService.staticInstance = pdf2SwfService;
		} else if ("stop".equals(mode)) {
			if (Pdf2SwfService.staticInstance != null) {
				try {
					Pdf2SwfService.stop = true;
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}

下面编译安装服务的脚本:

@echo off
cd /d %~dp0
set PR_PATH=%CD%
SET PR_SERVICE_NAME=Pdf2Swf
SET PR_JAR=pdf2swf.jar
SET START_CLASS=org.haifi.Pdf2SwfService
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% -out %CD%\stdout.log -err %CD%\stderr.log -current %CD%

echo %PR_PATH%

prunsrv.exe //IS//%PR_SERVICE_NAME% --DisplayName="%PR_SERVICE_NAME%" --Install=%PR_PATH%\prunsrv.exe --LogPath=%PR_PATH%\logs --LogLevel=Debug --StdOutput=auto --StdError=auto --StartMode=Java --StopMode=Java --Jvm=auto --StartMode=jvm --StartClass=%START_CLASS% ++StartParams=start --StopMode=jvm --StopClass=%STOP_CLASS% ++StopParams=stop --Classpath="%PR_PATH%\%PR_JAR%"  ++JvmOptions=%JVM_OPTIONS%
pause


上面的类换为自己写的主类名。

如果启动不起来时,注意一下如果jdk为32位版本时,需要使用32位的prunsrv。

如果使用64位的prunsrv,则必须使用64位的jdk版本。

不然会直接提示无法启动,但又不会有任何有用的提示信息。

发表评论?

0 条评论。

发表评论


注意 - 你可以用以下 HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>


Warning: Use of undefined constant XML - assumed 'XML' (this will throw an Error in a future version of PHP) in /opt/wordpress/wp-content/plugins/wp-syntaxhighlighter/wp-syntaxhighlighter.php on line 1048