Last active
August 29, 2015 14:25
-
-
Save int32at/2774e7f215ada53d1c38 to your computer and use it in GitHub Desktop.
sample random timer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class App { | |
public static void main(String[] args) { | |
// create new timer | |
MyTimer timer = new MyTimer(); | |
// add listener | |
timer.addListener(new MyTimer.IMyTimerEventListener() { | |
@Override | |
public void onEventFired() { | |
System.out.println("event fired"); | |
} | |
}); | |
// start the timer | |
timer.start(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
import java.util.Random; | |
public class MyTimer extends Thread { | |
public interface IMyTimerEventListener { | |
void onEventFired(); | |
} | |
// list of listeners that will be notified about the event | |
private ArrayList<IMyTimerEventListener> listeners; | |
// maximum sleep time in seconds | |
private static final int MAX_SLEEP_TIME = 30; | |
// minimum sleep time in seconds | |
private static final int MIN_SLEEP_TIME = 1; | |
// create new random | |
private static final Random rnd = new Random(); | |
public MyTimer() { | |
this.listeners = new ArrayList<IMyTimerEventListener>(); | |
} | |
public void addListener(IMyTimerEventListener listener) { | |
if (listener == null) | |
throw new IllegalArgumentException("listener"); | |
if (!listeners.contains(listener)) | |
listeners.add(listener); | |
} | |
@Override | |
public void run() { | |
// while the thread is alive | |
while (!isInterrupted()) { | |
try { | |
// get random value between max and min | |
int randomTimeToSleep = rnd.nextInt((MAX_SLEEP_TIME - MIN_SLEEP_TIME) + 1) | |
+ MIN_SLEEP_TIME; | |
// let the thread sleep for random amount of time | |
Thread.sleep(randomTimeToSleep * 1000); | |
} catch (InterruptedException e) { | |
// thread couldn't sleep, maybe throw exception here | |
} | |
// execute event and notify listeners | |
notifyListeners(); | |
} | |
} | |
private void notifyListeners() { | |
// iterate all attached listeners and fire event | |
for (IMyTimerEventListener listener : listeners) { | |
listener.onEventFired(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment