01: // Copyright (C) 2003,2004,2005 by Object Mentor, Inc. All rights reserved.
02: // Released under the terms of the GNU General Public License version 2 or later.
03: package fitnesse.schedule;
04:
05: import java.util.*;
06:
07: public class ScheduleImpl implements Schedule, Runnable {
08: private long delay;
09:
10: private Thread thread;
11:
12: private boolean running;
13:
14: private List scheduleItems = Collections
15: .synchronizedList(new LinkedList());
16:
17: public ScheduleImpl(long delay) {
18: this .delay = delay;
19: }
20:
21: public void add(ScheduleItem item) {
22: scheduleItems.add(item);
23: }
24:
25: public void start() {
26: running = true;
27: thread = new Thread(this );
28: thread.setPriority(Thread.MIN_PRIORITY);
29: thread.start();
30: }
31:
32: public void stop() throws Exception {
33: running = false;
34: if (thread != null) {
35: thread.join();
36: }
37: thread = null;
38: }
39:
40: public void run() {
41: try {
42: while (running) {
43: runScheduledItems();
44: Thread.sleep(delay);
45: }
46: } catch (Exception e) {
47: }
48: }
49:
50: public void runScheduledItems() throws Exception {
51: long time = System.currentTimeMillis();
52: synchronized (scheduleItems) {
53: for (Iterator iterator = scheduleItems.iterator(); iterator
54: .hasNext();) {
55: ScheduleItem item = (ScheduleItem) iterator.next();
56: runItem(item, time);
57: }
58: }
59: }
60:
61: private void runItem(ScheduleItem item, long time) throws Exception {
62: try {
63: if (item.shouldRun(time))
64: item.run(time);
65: } catch (Exception e) {
66: e.printStackTrace();
67: }
68: }
69: }
|