1 package fri.util; 2 3 6 7 public class TimeStopper 8 { 9 private long time1 = 0L, time2 = 0L; 10 private long timeSum = 0L; 11 private long lastIntervalStop = 0L; 12 13 14 15 public TimeStopper() { 16 this(true); 17 } 18 19 20 public TimeStopper(boolean doStart) { 21 if (doStart) 22 resume(); 23 } 24 25 26 public boolean isRunning() { 27 return time1 > 0L; 28 } 29 30 34 public void suspend() { 35 if (isRunning()) { 36 time2 = System.currentTimeMillis(); 37 timeSum += time2 - time1; 38 time1 = time2 = 0L; 39 } 40 } 41 42 46 public void resume() { 47 if (isRunning() == false) 48 lastIntervalStop = time1 = time2 = System.currentTimeMillis(); 49 } 50 51 52 public String stop() { 53 return getTime(true); 54 } 55 56 57 public void start() { 58 resume(); 59 timeSum = 0L; 60 } 61 62 66 public String getTime() { 67 return getTime(false); 68 } 69 70 private String getTime(boolean doStop) { 71 suspend(); 72 long elapsed = timeSum / 1000L; 73 long sec = elapsed % 60L; 74 long min = elapsed / 60L; 75 if (min > 60L) 76 min = min % 60L; 77 long hours = elapsed / 3600L; 78 if (doStop == false) 79 resume(); 80 return hours+":"+min+":"+sec; 81 } 82 83 87 public String getTimeMillis() { 88 suspend(); 89 resume(); 90 return new Long (timeSum).toString(); 91 } 92 93 96 public String stopMillis() { 97 suspend(); 98 return new Long (timeSum).toString(); 99 } 100 101 104 public String getInterval() { 105 long time = System.currentTimeMillis(); 106 long interval = time - lastIntervalStop; 107 lastIntervalStop = time; 108 return new Long (interval).toString(); 109 } 110 111 112 113 115 public static final void main(String [] args) { 116 TimeStopper timer = new TimeStopper(); 117 try { Thread.sleep(2000); } catch (Exception e) {} 118 System.err.println(timer.stop()); 119 } 120 121 } | Popular Tags |