Java/Tip & Tech2012. 1. 6. 23:49
[ 2010년 01월 27일 에 작성한 글입니다 ]

Java 응용프로그램을 만들면 모하나.. Windows 가 시작되면서 자동으로 이 프로그램을 구동시키려면 Windows 서비스에 등록해야만 하는데..

예전 회사에서 KT회선을 쓰고 있을때 퇴근하고 난뒤 2~3시간만 지나면 회사서버에 접속이 되지 않았었지.. 그래서 난 java 로 1시간에 한번씩 특정사이트를 호출하게 만드는 어플리케이션을 만들고 이것을 회사 서버에 윈도우 서비스에 등록해서 우리 회사서버를 외부에서 언제나 접속하게 했던 기억이나.. 이렇게 만들어놓음으로써 회사에는 언제나 사람이 브라우저를 사용하는 것처럼 될테고.. KT는 서버로의 접근을 차단할 근거가 없어지게 되니깐~~ ^^

[방법 1] Java Service Wrapper 를 이용하는 방법

http://wrapper.tanukisoftware.org 를 잘 참조하면 되겠어..
Profession 은 상용이지만 Community 버전은 프리하게 사용가능한가바. 문서도 좀 읽어야 가능하겠는걸?

[방법 2] JavaService 를 사용하는 방법

이건 좀 자세히 설명할꺼야.. 오늘 내가 직접 해볼꺼거등 ^^

[STEP 1] 프로그램 다운로드

http://javaservice.objectweb.org (http://forge.ow2.org/projects/javaservice/)
2010년 01월 27일 현재 "JavaService-2.0.10.zip" 이 나와있네...
압축파일을 풀면 많은 JavaService.exe 라는 파일이 있어.. 그게 젤 중요하니 한번 살펴보자...
(다른 bat 파일들은 이름만 살펴봐도 그 용도를 알 수 있을꺼야..)
JavaService.exe 을 C:\temp 에 한번 복사해놓고 테스트해보자구..



[STEP2] JavaService 의 install 옵션 둘러보기


자.. 도스커멘드에서 JavaService 어떻게 사용하나 알아보려고 "-help" 옵션으로 실행시킨 결과야..
-----------------------------------------------------------------------------------------------------
JavaService (Windows NT Service Daemon) commands:-
        -version
        -licence
        -install service_name jvm service_options...
        -queryconfig service_name
        -status service_name
        -uninstall service_name
        -help
        -help topic
-----------------------------------------------------------------------------------------------------

빨간 install 옵션이 제일 중요하니 어떻게 쓰는지 살펴보기 위해 다시한번 "-help install" 을 해보자고..
-----------------------------------------------------------------------------------------------------


To configure and install a background service:
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]
Where:
  service_name: The name of the service. ← 서비스명
  jvm_library:  The location of the JVM DLL used to run the service.  ← jvm.dll 위치
  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).
-----------------------------------------------------------------------------------------------------
저 위에서 service_name, jvm_library, start_class 옵션 정도만 사용해서 한번 install 해볼 예정이야..
jvm_option 은 필요할때 사용하고, start_method 는 대부분 main() 일테니 생략하자구..

[STEP3] 테스트 java 클래스 만들기

지금 테스트 하려고 하는데.. 아.. 간단한 클래스 없을까 하다가..
간단하게 10초에 한번씩 standard out으로 "hello word"를 찍는 클래스를 만들어보려구 해..
Timer 나 TimerTask 에 대한 것은 API를 참조해바바.. (자꾸 말로 물어서 해결하려하지 말구...)
-----------------------------------------------------------------------------------------------------
package test;

import java.util.Timer;
import java.util.TimerTask;

public class HelloWorldPrinter extends TimerTask {
    private static int count = 0;
    public void run() {
        count ++;
        System.out.println(count + " : Hello World !");
    }

    public static void main(String[] args) {
        HelloWorldPrinter printer = new HelloWorldPrinter();
        Timer timer = new Timer();
        timer.schedule(printer, 0, 10 * 1000);
    }
}
-----------------------------------------------------------------------------------------------------


이 클래스를 빌드해서 C:\temp\classes\test\HelloWorldPrinter.class 에 놓어보자구효~

[STEP4] Windows Service에 클래스 등록하기

아래와 같은 정보로 서비스를 등록해볼 참이야..
service_name : HelloWorldPrintingService
jvm_library : %JAVA_HOME%\jre\bin\server\jvm.dll
jvm_option : Djava.class.path=.\classes
start_class : test.HelloWorldPrinter
out_log_file : C:\temp\javaservice_test.log (테스트 결과확인을 위해 등록)
도스커멘드에서 아래의 커멘드를 실행시켜서 서비스로 등록을 해보자구..
-----------------------------------------------------------------------------------------------------
JavaService -install "HelloWorldPrinting Service" %JAVA_HOME%\jre\bin\server\jvm.dll -Djava.class.path=c:\temp\classes -start test.HelloWorldPrinter -out C:\temp\javaservice_test.log
-----------------------------------------------------------------------------------------------------


자.. 멋지게 등록되었고 SC를 이용해 서비스 등록상태까지 확인해봤어..

[STEP5] 서비스 실행하기

-----------------------------------------------------------------------------------------------------
net start "HelloWorldPrinting Service"
-----------------------------------------------------------------------------------------------------
이렇게 실행하고 서비스 등록시에 지정했던 로그파일을 보자구.. C:\temp\javaservice_test.log 에는 아래와 같이 찍혀있을꺼야..
1 : Hello World !
2 : Hello World !
3 : Hello World !
4 : Hello World !
5 : Hello World !
6 : Hello World !
7 : Hello World !
8 : Hello World !
9 : Hello World !
10 : Hello World !
성공이닷 !!

[STEP6] 서비스 종료하기
-----------------------------------------------------------------------------------------------------
net stop "HelloWorldPrinting Service"
-----------------------------------------------------------------------------------------------------

[STEP7] 서비스 삭제하기

-----------------------------------------------------------------------------------------------------
JavaService -uninstall "HelloWorldPrinting Service"
-----------------------------------------------------------------------------------------------------

파일 첨부해놨으니 쉽게 테스트 할수 있을꺼야.. 수고했샤~~
Posted by 꼰스