Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
ApacheCommonsDaemon
#!/bin/sh
NAME="testdaemon"
DESC="TestDaemon service"
# The path to Jsvc
EXEC="/usr/local/bin/jsvc"
# The path to the folder containing MyDaemon.jar
FILE_PATH="/usr/local/$NAME"
# The path to the folder containing the java runtime
JAVA_HOME="/Library/Java/JavaVirtualMachines/jdk1.8.0_40.jdk/Contents/Home"
# Our classpath including our jar file and the Apache Commons Daemon library
CLASS_PATH="$FILE_PATH/TestDaemon.jar:$FILE_PATH/lib/commons-daemon-1.0.15.jar"
# The fully qualified name of the class to execute
CLASS="com.tasknotes.daemon.TestDaemon"
#The user to run the daemon as
USER="root"
# The file that will contain our process identification number (pid) for other scripts/programs that need to access it.
PID="/var/run/$NAME.pid"
# System.out writes to this file...
LOG_OUT="$FILE_PATH/log/$NAME.out"
# System.err writes to this file...
LOG_ERR="$FILE_PATH/err/$NAME.err"
jsvc_exec()
{
cd $FILE_PATH
$EXEC -home $JAVA_HOME -cp $CLASS_PATH -user $USER -outfile $LOG_OUT -errfile $LOG_ERR -pidfile $PID $1 $CLASS
}
case "$1" in
start)
echo "Starting the $DESC..."
# Start the service
jsvc_exec
echo "The $DESC has started."
;;
stop)
echo "Stopping the $DESC..."
# Stop the service
jsvc_exec "-stop"
echo "The $DESC has stopped."
;;
restart)
if [ -f "$PID" ]; then
echo "Restarting the $DESC..."
# Stop the service
jsvc_exec "-stop"
# Start the service
jsvc_exec
echo "The $DESC has restarted."
else
echo "Daemon not running, no action taken"
exit 1
fi
;;
*)
echo "Usage: /etc/init.d/$NAME {start|stop|restart}" >&2
exit 3
;;
esac
package com.tasknotes.daemon;
import org.apache.commons.daemon.Daemon;
import org.apache.commons.daemon.DaemonContext;
import org.apache.commons.daemon.DaemonInitException;
public class TestDaemon implements Daemon {
private Thread thread;
private boolean stopped = false;
@Override
public void start() throws Exception {
thread.start();
}
@Override
public void stop() throws Exception {
stopped = true;
try {
thread.join();
} catch (InterruptedException e) {
System.err.println(e.getMessage());
throw e;
}
}
@Override
public void destroy() {
thread = null;
}
@Override
public void init(DaemonContext daemonContext) throws DaemonInitException, InterruptedException, Exception {
thread = new Thread() {
private long i = 0;
@Override
public void run() {
while(!stopped) {
System.out.println(i++);
try {
sleep(1000);
} catch (InterruptedException e) {
System.err.println(e.getMessage());
}
}
}
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.