001/* 002 * $Id: TimeStatus.java 4055 2012-07-26 17:37:29Z kredel $ 003 */ 004 005package edu.jas.kern; 006 007 008import java.util.concurrent.Callable; 009 010 011/** 012 * Run-time status, defines global status and handling for run time limits. 013 * @author Heinz Kredel 014 */ 015 016public class TimeStatus { 017 018 019 /** 020 * Global status flag. 021 */ 022 private static boolean allowTime = false; 023 024 025 /** 026 * Global run-time limit in milliseconds. 027 */ 028 private static long limitTime = Long.MAX_VALUE; 029 030 031 /** 032 * Global run-time limit in milliseconds. 033 */ 034 private static long startTime = System.currentTimeMillis(); 035 036 037 /** 038 * Call back method. true means continue, false means throw exception. 039 */ 040 private static Callable<Boolean> callBack = null; 041 042 043 /** 044 * No public constructor. 045 */ 046 protected TimeStatus() { 047 } 048 049 050 /** 051 * isActive. 052 * @return true, if run-time interruption is active, else false. 053 */ 054 public static boolean isActive() { 055 return allowTime; 056 } 057 058 059 /** 060 * setAllow, set run-time interruption to allowed status. 061 */ 062 public static void setActive() { 063 allowTime = true; 064 } 065 066 067 /** 068 * setNotActive, set run-time interruption to not active status. 069 */ 070 public static void setNotActive() { 071 allowTime = false; 072 } 073 074 075 /** 076 * setLimit, set run-time limit in milliseconds. 077 */ 078 public static void setLimit(long t) { 079 limitTime = t; 080 } 081 082 083 /** 084 * Restart timer, set run-time to current time. 085 */ 086 public static void restart() { 087 startTime = System.currentTimeMillis(); 088 } 089 090 091 /** 092 * set call back, set the Callabe object. 093 */ 094 public static void setCallBack(Callable<Boolean> cb) { 095 callBack = cb; 096 } 097 098 099 /** 100 * Check for exceeded time, test if time has exceeded and throw an exception 101 * if so. 102 * @param msg the message to be send with the exception. 103 */ 104 public static void checkTime(String msg) { 105 if (!allowTime) { 106 return; 107 } 108 if (limitTime == Long.MAX_VALUE) { 109 return; 110 } 111 long tt = (System.currentTimeMillis() - startTime - limitTime); 112 //System.out.println("tt = " + tt); 113 if (tt <= 0L) { 114 return; 115 } 116 if (callBack != null) { 117 try { 118 boolean t = callBack.call(); 119 if (t) { 120 return; 121 } 122 } catch (Exception e) { 123 } 124 } 125 if (msg == null) { 126 msg = ""; 127 } 128 throw new TimeExceededException(msg + " over time = " + tt); 129 } 130 131}