Skip to content

Instantly share code, notes, and snippets.

@wolfg1969
Created September 17, 2012 08:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save wolfg1969/3736281 to your computer and use it in GitHub Desktop.
Save wolfg1969/3736281 to your computer and use it in GitHub Desktop.
run java program as a daemon with jsvc
package server;
import org.apache.commons.daemon.Daemon;
import org.apache.commons.daemon.DaemonContext;
import org.apache.commons.daemon.DaemonInitException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* User: guoyong
* Date: 12-9-17 上午10:21
*/
public class DemoDaemon implements Daemon {
private final static Logger logger = LoggerFactory.getLogger(DemoDaemon.class);
@Override
public void init(DaemonContext context) throws DaemonInitException, Exception {
}
@Override
public void start() throws Exception {
Server.initialize();
Server.start();
}
@Override
public void stop() throws Exception {
// jsvc -stop using kill -15 to stop the process, so the real stop method
// should be called within a shutdown hook.
}
@Override
public void destroy() {
}
}
#!/bin/bash
if [ -z "$JAVA_HOME" ]; then
echo "JAVA_HOME is not set"
exit 1
fi
type jsvc >/dev/null 2>&1 || { echo >&2 "jsvc is not installed. Aborting."; exit 1; }
# Setup variables
SCRIPT=`readlink -f $0`
BASEDIR=$(cd $(dirname $SCRIPT)/..; pwd)
LIBS="$BASEDIR/lib"
EXEC=jsvc
CLASS_PATH="$BASEDIR/etc:$(echo $LIBS/*.jar | tr ' ' ':')"
CLASS=server.DemoDaemon
JVM_ARGS="-Xms1024m -Xmx1024m -Xss1m -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=9999 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false"
SYS_ENV="-Denv=PROD -Dlog.dir=$BASEDIR/logs"
USER=webmaster
PID=$BASEDIR/logs/server.pid
LOG_OUT=$BASEDIR/logs/server.out
LOG_ERR=$BASEDIR/logs/server.err
do_exec()
{
$EXEC -home "$JAVA_HOME" -cp $CLASS_PATH -user $USER $SYS_ENV $JVM_ARGS -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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment