Skip to content

Instantly share code, notes, and snippets.

@int32at
Last active August 29, 2015 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save int32at/2774e7f215ada53d1c38 to your computer and use it in GitHub Desktop.
Save int32at/2774e7f215ada53d1c38 to your computer and use it in GitHub Desktop.
sample random timer
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();
}
}
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