Running Java process as Service in Linux

15,611

You could try using jsvc from apache. Tomcat use it to be launched as a service.

Share:
15,611

Related videos on Youtube

mainstringargs
Author by

mainstringargs

Updated on June 05, 2022

Comments

  • mainstringargs
    mainstringargs almost 2 years

    I need to run a Java process as a service in (Red Hat 6.4) Linux (It needs to run at boot time and stay up). I have it mostly working, except for it doesn't seem to status correctly in the "Service Configuration" window.

    To illustrate, I made a simple Java program:

    package service;
    
    public class JavaService {
    
        public static void main(String args[]){
    
            System.out.println("Starting Java-Service");
            while(true){
    
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
    
                System.out.println("Java-Service is still running..");
            }
        }
    }
    

    I jarred that up, and put it at this location: /opt/service/lib

    Then, I created this script: /opt/service/bin/run_java_service

    #!/bin/tcsh
    #
    # chkconfig: 2345 80 30
    # description: java-service Service
    
    setenv JAVA_SERVICE_HOME /opt/service
    setenv CLASSPATH $JAVA_SERVICE_HOME/lib/JavaService.jar
    
    setenv SERVICE_PID  `ps aux | grep JavaService | grep -v grep | awk '{print $2}'`;
    
    if ( (stop == $1  || restart == $1)) then
        echo "java-service stop";
        kill -9 $SERVICE_PID
        setenv SERVICE_PID
    endif
    
    if ( start == $1 || restart == $1 ) then
        if($SERVICE_PID) then
            echo "java-service is already running"
        else
            echo "java-service start";
            java service.JavaService&
        endif
    endif
    
    if (status == $1) then
        if($SERVICE_PID) then
            echo "java-service (pid $SERVICE_PID) is running...";
        else
            echo "java-service is stopped";
        endif
    endif
    

    I then created a symlink to this in the /etc/rc.d/init.d directory and added it to the chkconfig:

    sudo ln –s /opt/service/bin/run_java_service /etc/rc.d/init.d/java-service
    sudo chkconfig --add java-service
    

    At this point, commands like this work as expected from the command line:

    sudo service java-service stop
    sudo service java-service start
    sudo service java-service status
    

    The problem is that things aren't statusing correctly in the "Service Configuration" dialog. For instance, in this screenshot, I have clicked the "Stop Button" and it still shows as "plugged in".

    enter image description here

    What piece of the puzzle am I missing?