added ImmortalThread
[org.ibex.util.git] / src / org / ibex / util / ImmortalThread.java
1 // Copyright 2000-2005 the Contributors, as shown in the revision logs.
2 // Licensed under the Apache Public Source License 2.0 ("the License").
3 // You may not use this file except in compliance with the License.
4
5 package org.ibex.util;
6 import java.util.*;
7 import java.net.*;
8 import java.io.*;
9
10 /** run cycle() repeatedly, no more often than minCycleTimeMillis; catch and log any exceptions. */
11 public abstract class ImmortalThread extends Thread {
12     
13     private final int minCycleTimeMillis;
14     public ImmortalThread() { this(500); }
15     public ImmortalThread(int minCycleTimeMillis) { this.minCycleTimeMillis = minCycleTimeMillis; }
16     
17     public abstract void cycle() throws Exception;
18
19     public final void run() {
20         while(true) {
21             long now = System.currentTimeMillis();
22             try {
23                 cycle();
24             } catch (Exception e) { Log.warn(this, e); }
25             long now2 = System.currentTimeMillis();
26             if (now2 - now < minCycleTimeMillis)
27                 try { Thread.sleep(minCycleTimeMillis - (now2 - now)); } catch (Exception e) { }
28         }
29     }
30
31 }