1 package org.jmux.app.component;
2
3 import org.jmux.app.App;
4 import org.jmux.app.component.config.Config;
5 import org.jmux.app.component.jmx.JMX;
6
7 /******************************************************************************
8 jmux - Java Modules Using XML
9 Copyright © 2006 jmux.org
10
11 This library is free software; you can redistribute it and/or
12 modify it under the terms of the GNU Lesser General Public
13 License as published by the Free Software Foundation; either
14 version 2.1 of the License, or (at your option) any later version.
15
16 This library is distributed in the hope that it will be useful,
17 but WITHOUT ANY WARRANTY; without even the implied warranty of
18 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 Lesser General Public License for more details.
20
21 You should have received a copy of the GNU Lesser General Public
22 License along with this library; if not, write to the Free Software
23 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
24 *****************************************************************************/
25
26 /***
27 * @author donaldw
28 */
29 public abstract class AbstractLoopingComponent extends AbstractControl {
30
31 private static final int DEFAULT_LOOP_TIME = 10000;
32
33 private Thread thread;
34 private int period;
35
36 public void configure(Config config, App app) {
37 super.configure(config, app);
38 period = config.getInteger(DEFAULT_LOOP_TIME, "period");
39 }
40
41 public void start() {
42 if (!isRunning()) {
43 thread = new Thread(new Runnable() {
44 public void run() {
45 doLoop();
46 }
47 });
48 thread.setName(this.getClass().getName());
49 thread.start();
50 }
51 }
52
53 public void stop() {
54 if (isRunning()) {
55 thread.interrupt();
56 }
57 }
58
59 @JMX
60 private boolean isRunning() {
61 return (thread != null);
62 }
63
64 /***
65 * Loops runs until an exception is thrown, or until the thread is interrupted.
66 */
67 private void doLoop() {
68 try {
69 while (!thread.isInterrupted()) {
70 try {
71 doWork();
72 Thread.sleep(period);
73 } catch (InterruptedException e) {
74 break;
75 }
76 }
77 } finally {
78 thread = null;
79 }
80 }
81
82 protected abstract void doWork();
83 }