1 package Jt.examples.patterns; 2 3 import Jt.*; 4 import java.io.*; 5 import java.util.*; 6 import Jt.xml.*; 7 8 9 13 14 15 public class Timer extends JtCommand { 16 17 private long tstart; private long tend; private double time; 21 public Timer() { 22 this.setSynchronous (false); } 24 25 26 28 public double getTime () { 29 return (time); 30 } 31 32 33 public void setTime (double time) { 34 this.time = time; 35 } 36 37 39 public Object processMessage (Object message) { 40 41 String msgid = null; 42 JtMessage msg = (JtMessage) message; 43 Object content; 44 45 if (msg == null) 46 return null; 47 48 msgid = (String ) msg.getMsgId (); 49 50 if (msgid == null) 51 return null; 52 53 content = msg.getMsgContent(); 54 55 57 if (msgid.equals ("START_TIMER")) { 58 59 tstart = (new Date()).getTime (); 60 61 logMessage (msg); 63 sendMessage (this, new JtMessage ("CHECK_TIMER")); 64 return (null); 65 } 66 67 69 if (msgid.equals ("CHECK_TIMER")) { 70 71 tend = (new Date ()).getTime (); 72 time = (tend - tstart)/1000.0; 73 System.out.println ("Timer:" + time); 74 75 77 sendMessage (this, new JtMessage ("CHECK_TIMER")); 78 79 return (null); 80 } 81 82 84 if (msgid.equals ("STOP_TIMER")) { 85 86 tend = (new Date ()).getTime (); 87 time = (tend - tstart)/1000.0; 88 sendMessage (this, new JtMessage ("JtSTOP")); 89 90 logMessage (msg); 92 return (null); 93 } 94 95 96 98 if (msgid.equals ("JtREMOVE") || msgid.equals ("JtSTART") || msgid.equals ("JtSTOP")) { 99 return (super.processMessage (message)); 100 } 101 102 handleError ("Timer.processMessage: invalid message id:" + msgid); 103 return (null); 104 105 } 106 107 static private char waitForInputKey () { 108 char c = ' '; 109 110 try { 111 112 c = (char) System.in.read (); 113 while (System.in.available () > 0) 114 System.in.read (); 115 116 } catch (Exception e) { 117 e.printStackTrace (); 118 } 119 120 return (c); 121 } 122 123 125 public static void main(String [] args) { 126 127 JtObject main = new JtFactory (); 128 JtMessage msg, msg1; 129 JtXMLHelper xmlHelper = new JtXMLHelper (); 130 131 132 133 134 136 main.createObject ("Jt.examples.patterns.Timer", "timer"); 137 138 System.out.println ("Press any key to start/stop the timer ...."); 139 waitForInputKey (); 140 141 143 main.sendMessage ("timer", new JtMessage ("START_TIMER")); 144 145 146 waitForInputKey (); 148 149 150 main.sendMessage ("timer", new JtMessage ("STOP_TIMER")); 151 152 System.out.println (main.getValue ("timer", "time") + " second(s) elapsed"); 153 154 156 main.removeObject ("timer"); 157 158 } 159 160 } 161 162 163 164 | Popular Tags |