1 package example; 2 3 import com.caucho.log.Log; 4 import com.caucho.util.L10N; 5 import java.util.logging.Level ; 6 import java.util.logging.Logger ; 7 8 public class PeriodicTask 9 implements PeriodicTaskMBean, javax.resource.spi.work.Work 10 { 11 static protected final Logger log = 12 Logger.getLogger(PeriodicTask.class.getName()); 13 14 private long _estimatedAverageTime = 5000; 15 16 private boolean _isActive = false; 17 private long _lastActiveTime = -1; 18 private long _totalActiveCount = 0; 19 private long _totalActiveTime = 0; 20 21 22 public PeriodicTask() 23 { 24 } 25 26 29 public void setEstimatedAverageTime(long estimatedAverageTime) 30 { 31 _estimatedAverageTime = estimatedAverageTime; 32 } 33 34 37 public long getEstimatedAverageTime() 38 { 39 return _estimatedAverageTime; 40 } 41 42 public void init() 43 throws Exception 44 { 45 } 46 47 50 public boolean isActive() 51 { 52 synchronized (this) { 53 return _isActive == true; 54 } 55 } 56 57 60 public long getEstimatedTimeRemaining() 61 { 62 synchronized (this) { 63 if (_isActive) { 64 long now = System.currentTimeMillis(); 65 long activeTime = now - _lastActiveTime; 66 long estimate = getAverageActiveTime() - activeTime; 67 if (estimate < 0) 68 return 1000; 69 else 70 return estimate; 71 } 72 else 73 return 0; 74 } 75 } 76 77 80 public long getLastActiveTime() 81 { 82 return _lastActiveTime; 83 } 84 85 88 public long getTotalActiveCount() 89 { 90 return _totalActiveCount; 91 } 92 93 96 public long getTotalActiveTime() 97 { 98 return _totalActiveTime; 99 } 100 101 104 public long getAverageActiveTime() 105 { 106 synchronized (this) { 107 long count = _isActive ? _totalActiveCount -1 : _totalActiveCount; 108 if (count < 1) 109 return _estimatedAverageTime; 110 else 111 return _totalActiveTime / count; 112 } 113 } 114 115 121 public void run() 122 { 123 synchronized (this) { 124 if (_isActive == true) 125 return; 126 _isActive = true; 127 128 _lastActiveTime = System.currentTimeMillis(); 129 _totalActiveCount++; 130 } 131 132 try { 133 log.fine("performing task"); 134 135 performTask(); 136 137 log.fine("done performing task"); 138 } 139 catch (Exception ex) { 140 log.log(Level.WARNING,"task failed",ex); 141 } 142 finally { 143 synchronized (this) { 144 _totalActiveTime += (System.currentTimeMillis() - _lastActiveTime); 145 _isActive = false; 146 } 147 } 148 } 149 150 protected void performTask() 151 throws Exception 152 { 153 Thread.sleep(10 * 1000L); 156 } 157 158 161 public void release() 162 { 163 } 164 } 165 166 | Popular Tags |