01: package example;
02:
03: import java.util.*;
04: import java.util.concurrent.*;
05:
06: import javax.webbeans.Component;
07: import javax.webbeans.In;
08:
09: import com.caucho.servlet.comet.*;
10:
11: @Component
12: public class TimerService implements Runnable {
13: private ScheduledExecutorService _timer;
14:
15: private Future _timerFuture;
16:
17: private ArrayList<CometState> _stateList = new ArrayList<CometState>();
18:
19: public TimerService(@In
20: ScheduledExecutorService timer) {
21: _timer = timer;
22:
23: _timerFuture = _timer.scheduleAtFixedRate(this , 0, 2,
24: TimeUnit.SECONDS);
25: }
26:
27: public void addCometState(CometState state) {
28: synchronized (_stateList) {
29: _stateList.add(state);
30: }
31: }
32:
33: /**
34: * The timer task wakes up every active comet state.
35: *
36: * A more sophisticated application would notify the comet states
37: * as part of an event-based system.
38: */
39: public void run() {
40: synchronized (_stateList) {
41: for (int i = _stateList.size() - 1; i >= 0; i--) {
42: CometState state = _stateList.get(i);
43:
44: if (!state.wake())
45: _stateList.remove(i);
46: }
47: }
48: }
49:
50: /**
51: * Close the timer.
52: */
53: public void close() {
54: _timerFuture.cancel(false);
55: }
56: }
|