1 /***
2 *
3 * Copyright 2005 LogicBlaze, Inc. http://www.logicblaze.com
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 **/
18 package org.logicblaze.lingo.util;
19
20 import edu.emory.mathcs.backport.java.util.concurrent.ScheduledExecutorService;
21 import edu.emory.mathcs.backport.java.util.concurrent.TimeUnit;
22
23 import org.apache.commons.logging.Log;
24 import org.apache.commons.logging.LogFactory;
25
26 /***
27 * A simple POJO which is useful for wiring together tasks in an IoC type way.
28 *
29 * @version $Revision$
30 */
31 public class ScheduledTask implements Runnable {
32
33 private static final Log log = LogFactory.getLog(ScheduledTask.class);
34
35 private ScheduledExecutorService executor;
36 private Runnable task;
37 private long timeoutMillis;
38
39 public ScheduledTask(Runnable task, ScheduledExecutorService executor, long millis) {
40 this.task = task;
41 this.executor = executor;
42 this.timeoutMillis = millis;
43 scheduleTask();
44 }
45
46 /***
47 * Performs the task and then schedules another execution of the task.
48 */
49 public void run() {
50 try {
51 task.run();
52 }
53 catch (RuntimeException e) {
54 log.warn("Caught exception while running task: " + task + ". Detail: " + e, e);
55 }
56 scheduleTask();
57 }
58
59 public void stop() {
60 executor = null;
61 }
62
63
64
65 public long getTimeoutMillis() {
66 return timeoutMillis;
67 }
68
69 public void setTimeoutMillis(long timeoutMillis) {
70 this.timeoutMillis = timeoutMillis;
71 }
72
73
74
75 protected void scheduleTask() {
76 if (executor != null) {
77 executor.schedule(this, timeoutMillis, TimeUnit.MILLISECONDS);
78 }
79 }
80
81 }