How to Daemonize a Java Program

How to Daemonize a Java Program?

Apache Commons Daemon will run your Java program as Linux daemon or WinNT Service.

Best way to daemonize Java application on Linux

While the standard answer to this seems to be jsvc, I have been using djb's daemon tools to be a great way to make anything into a daemon.

I have java, python and a few shell scripts all running as daemons, with a simple way to start/stop them and great logging.

I've used to run daemontools itself as root on initctl as originally designed, but after a few months I decided to run it manually, under a normal user, and using svscan-start for nicer logging.

How to convert a java program to daemon with jsvc?

Java class:

package example;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import org.apache.commons.daemon.*;

class EchoTask extends TimerTask {
@Override
public void run() {
System.out.println(new Date() + " running ...");
}
}

public class Main implements Daemon {

private static Timer timer = null;

public static void main(String[] args) {
timer = new Timer();
timer.schedule(new EchoTask(), 0, 1000);
}

@Override
public void init(DaemonContext dc) throws DaemonInitException, Exception {
System.out.println("initializing ...");
}

@Override
public void start() throws Exception {
System.out.println("starting ...");
main(null);
}

@Override
public void stop() throws Exception {
System.out.println("stopping ...");
if (timer != null) {
timer.cancel();
}
}

@Override
public void destroy() {
System.out.println("done.");
}

}

Shell start/stop script:

#!/bin/sh

# Setup variables
EXEC=/usr/bin/jsvc
JAVA_HOME=/usr/lib/jvm/java-6-sun
CLASS_PATH="/usr/share/java/commons-daemon.jar":"/path/to/your.jar"
CLASS=example.Main
USER=foo
PID=/tmp/example.pid
LOG_OUT=/tmp/example.out
LOG_ERR=/tmp/example.err

do_exec()
{
$EXEC -home "$JAVA_HOME" -cp $CLASS_PATH -user $USER -outfile $LOG_OUT -errfile $LOG_ERR -pidfile $PID $1 $CLASS
}

case "$1" in
start)
do_exec
;;
stop)
do_exec "-stop"
;;
restart)
if [ -f "$PID" ]; then
do_exec "-stop"
do_exec
else
echo "service not running, will do nothing"
exit 1
fi
;;
*)
echo "usage: daemon {start|stop|restart}" >&2
exit 3
;;
esac

And the effect:

$ ./service start && sleep 5 && ./service stop
$ cat /tmp/example.out
initializing ...
starting ...
Fri Oct 07 16:26:54 EEST 2011 running ...
Fri Oct 07 16:26:55 EEST 2011 running ...
Fri Oct 07 16:26:56 EEST 2011 running ...
Fri Oct 07 16:26:57 EEST 2011 running ...
Fri Oct 07 16:26:58 EEST 2011 running ...
stopping ...
done.

start-stop-daemon and java - how to do it right?

I suggest DaemonTools + service/chkconfig.

DaemonTools maybe already installed on your platform, or you can try apt-get. It will restart your daemon automatically in at most 5 seconds.

You can look up linux user manual 8 for more information about service/chkconfig.

Hope this helpful.



Related Topics



Leave a reply



Submit