我刚刚用Apache Commons Daemon编写了一个小的简单守护程序,该守护程序与jsvc一起运行。这是我当前运行守护程序的方式:
CLASS_PATH="/usr/share/java/commons-daemon.jar":"/home/myuser/myproject/build/libs/JsvcHelloWorld-1.0-SNAPSHOT.jar"
PID=/tmp/myjsvcdaemon.pid
LOG_OUT=/tmp/myjsvcdaemon.out
LOG_ERR=/tmp/myjsvcdaemon.err
CLASS=JsvcHelloWorld
jsvc -home "$JAVA_HOME" -cp $CLASS_PATH -user $USER -outfile $LOG_OUT -errfile $LOG_ERR -pidfile $PID $1 $CLASS
这是我的Daemon Java文件的样子:
import org.apache.commons.daemon.Daemon;
import org.apache.commons.daemon.DaemonContext;
import org.apache.commons.daemon.DaemonInitException;
public class JsvcHelloWorld2 implements Daemon {
private Thread myThread;
private boolean stopped = false;
private boolean lastOneWasATick = false;
@Override
public void init(DaemonContext daemonContext) throws DaemonInitException, Exception {
/*
* Construct objects and initialize variables here.
* You can access the command line arguments that would normally be passed to your main()
* method as follows:
*/
String[] args = daemonContext.getArguments();
myThread = new Thread() {
private long lastTick = 0;
@Override
public synchronized void start() {
JsvcHelloWorld2.this.stopped = false;
super.start();
}
@Override
public void run() {
while (!stopped) {
long now = System.currentTimeMillis();
if (now - lastTick >= 1000) {
System.out.println(!lastOneWasATick ? "tick" : "tock");
lastOneWasATick = !lastOneWasATick;
lastTick = now;
}
}
}
};
}
@Override
public void start() throws Exception {
myThread.start();
}
@Override
public void stop() throws Exception {
stopped = true;
try {
myThread.join(1000);
} catch (InterruptedException e) {
System.err.println(e.getMessage());
throw e;
}
}
@Override
public void destroy() {
myThread = null;
}
}
如您所见,守护程序中没有main方法,有人知道如何在IntelliJ中调试jsvc守护程序吗?请帮助,任何人! :)