tag:blogger.com,1999:blog-10834433155167944222024-03-13T22:44:15.281-07:00Wajid's Technology BlogThis Blog is to share and discuss my experience with different technologies and moreover it has been some time since I did make my presence felt on the internet.Wajidhttp://www.blogger.com/profile/15743746424395488989noreply@blogger.comBlogger1125tag:blogger.com,1999:blog-1083443315516794422.post-52274774475183688832009-05-30T09:10:00.000-07:002009-05-30T11:11:27.247-07:00Java Program as a Daemon<div><span style="color:#000000;">After my pursuit for a source on the web that would help me accomplish this, I realized that I should share it and it might save you some time.<br />So this is exactly what we are trying to do. Make a Java Program run as a Daemon in the UNIX Environment and do a few checks and ensure that we are in control of the Daemon that we have started. We would also avoid dependencies, such that our approach works across all flavors of Unix. So let’s get started.</span><br /><span style="color:#000000;"></span><br /><br /><br /><br /><ul><br /><br /><li><span style="color:#000000;">We will start with a simple Java class ‘JavaDaemonTest’ that runs a recursive loop in the main method to log the Time Stamp after every three seconds to a text file.</span></li></ul><br /><br /><p align="justify"><span style="font-family:courier new;">public class JavaDaemonTest {<br />public static void main (String[] args) {<br />try {<br />while (true) {<br />Thread.sleep (3000);<br />log ("running"); }}<br />//The log method is defined below<br />catch (Throwable t) {<br />log ("Exception: "+t.toString()); }}</span></p><br /><br /><p align="justify"><span style="font-family:courier new;"><br />private static void log (String msg) {<br />BufferedWriter out=null;<br />FileWriter fstream =null;<br />try{<br />fstream = new FileWriter("out.txt",true);<br />//the message is written to the text file out.txt<br />out = new BufferedWriter(fstream);<br />out.write('\n'+getTimeStamp()+""+msg);<br />//the getTimeStamp() method is defined below<br />}catch(Exception e){<br />e.printStackTrace();<br />}<br />finally{<br />//Close the output stream<br />try{<br />out.close();<br />}catch(Exception e){<br />}<br />}<br />}<br /></span></p><br /><br /><p align="justify"><span style="font-family:courier new;">private static String getTimeStamp() {<br />SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");<br />return f.format(new Date()); }<br />} // end class JavaDaemonTest<br /></span></p><br /><br /><ul><br /><br /><li><span style="color:#000000;">Now if we want to have this Java Class run as a daemon it is recommended to have a Shut Down Hook attached to the main method which would ensure that the Daemon terminates properly and we can associate some events to this Daemon to be triggered when the thread is shutdown.Our shell script that starts this Daemon would create a plain text file with the process ID(PID) of the Daemon. And now we add a few lines to our Java Code.</span></li></ul><br /><br /><p><span style="font-family:courier new;">import java.io.BufferedWriter;<br />import java.io.FileWriter;<br />import java.io.File;<br />import java.text.SimpleDateFormat;<br />import java.util.Date;<br /><br />public class JavaDaemonTest {<br /><br />private static final int shutdownTime = 2;<br />// Initialize a variable to add a delay after the Daemon ShutDown //is invoked<br /><br />public static void main (String[] args) {<br /><br />log ("JavaDaemonTest started");<br /><br />//We create a new thread object which calls the<br />//shutdownHook</span><span style="font-family:courier new;">() method defined below<br />Thread runtimeHookThread = new Thread() {<br />public void run() {<br />shutdownHook(); }};<br />//Pass the above defined thread object reference<br /></span><span style="font-family:courier new;">//to the addShutdownHook() method which is a predefined method<br /></span><span style="font-family:courier new;">// to watch the shutdown of the main method.<br />Runtime.getRuntime().addShutdownHook (runtimeHookThread);<br />try {<br />while (true) {<br />Thread.sleep (3000);<br />log ("running"); }}<br />catch (Throwable t) {<br />log ("Exception: "+t.toString()); }}<br />//This method is called when the Daemon is shutdown<br /></span></p><br /><br /><p><span style="font-family:courier new;">private static void shutdownHook() {<br />log ("ShutdownHook started");<br />long t0 = System.currentTimeMillis();<br />while (true) {<br />try {<br />Thread.sleep (500); }<br />catch (Exception e) {<br />log ("Exception: "+e.toString());<br />break; }<br />//we wait for 2 seconds before we break from the loop.<br />if (System.currentTimeMillis() - t0 > shutdownTime*1000) break;<br />log ("shutdown"); }<br />log ("ShutdownHook completed");<br />//Check for the existence of the text file<br />//<> created to hold the PID<br />//by the shell script and delete it on Daemon shutdown.<br />if(new File("ActiveDaemonPID.pid").exists())<br />if(new File("ActiveDaemonPID.pid").delete())<br />log ("ActiveDaemonPID.pid file deleted");<br />}<br /><br />private static void log (String msg) {<br />BufferedWriter out=null;<br />FileWriter fstream =null;<br />try{<br />fstream = new FileWriter("out.txt",true);<br />out = new BufferedWriter(fstream);<br />out.write('\n'+getTimeStamp()+""+msg);<br />}catch(Exception e){<br />e.printStackTrace();<br />}<br />finally{<br />//Close the output stream<br />try{<br />out.close();<br />}catch(Exception e){<br />}<br />}<br />}<br /><br />private static String getTimeStamp() {<br />SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");<br />return f.format(new Date()); }<br />} // end class JavaDaemonTest<br /></p></span><br /><br /><ul><br /><br /><li><span style="color:#000000;">And now the final step is creating a shell script which would run the Daemon. Our shell script would check for the existence of a file called ‘ActiveDaemonPID.pid’ and if not found it starts our java code as a Daemon and writes the PID to the file ‘ActiveDaemonPID.pid’. If you can recollect the shutdownHook()method of our Java Code we delete the file ‘ActiveDaemonPID.pid’ when the Daemon stops. And here is our shell script </span></li></ul><br /><img id="BLOGGER_PHOTO_ID_5341667253798360018" alt="" src="http://4.bp.blogspot.com/_53AufAOq8HM/SiFqEOL809I/AAAAAAAAAJ4/1dCWGjNp2IM/s400/img.bmp" border="0" /><br /><br /><p>if [ -f /home/wajidmehraj/ServiceDaemon/ActiveDaemonPID.pid ]<br />then<br />echo "Daemon already in progress"<br />else<br />java JavaDaemonTest <&- & pid=\$! if ps -p "\${pid}" >/dev/null 2>&1<br />then<br />echo \${pid} > ActiveDaemonPID.pid<br />else<br />echo \daemon failed to start. >DaemonFailiureStatusFile<br />fi<br />fi</p><br /><p>EOF</p><br /><p><span style="color:#000000;">In case the Daemon fails to start and no PID is associate to it we write the text ‘daemon failed to start’ to the DaemonFailiureStatusFile file.<br /><br />So that is all you need to have the Daemon working. </span></p><br /><br /><p><span style="color:#000000;"></span></p><br /></div>Wajidhttp://www.blogger.com/profile/15743746424395488989noreply@blogger.com1