Scenario: Notify Multiple observers on timer event.
Approach :
- Create Watchdog class which creates the timer.
- Observers register to Watchdog event.
- Watchdog class on timer event notifies the observers.
Sample Code :
// WatchDog.java
import java.util.Observable;
import java.util.Observer;
import java.util.Timer;
import java.util.TimerTask;
// Observer class
class Observer1 implements Observer{
@Override
public void update(Observable arg0, Object arg1) {
System.out.println("Observer1 notified");
}
}
// Watchdog Component which creates the timer and notifies the timers.
public class WatchDog extends Observable {
Timer timer;
int seconds;
// Notify task to notify observers
class NotifyTask extends TimerTask{
@Override
public void run() {
setChanged();
notifyObservers();
}
}
public WatchDog( ) {
timer = new Timer();
}
public void schedule(long seconds){
timer.scheduleAtFixedRate(new NotifyTask(), 0, seconds*1000); //delay in milliseconds
}
public void stop(){
timer.cancel();
}
public static void main(String args[]) throws InterruptedException {
Observer1 observer1 = new Observer1();
WatchDog watchDog = new WatchDog();
// register with observer
watchDog.addObserver(observer1);
System.out.println("WatchDog is scheduled.");
watchDog.schedule(5);
Thread.sleep(25000);
watchDog.stop();
}
}