KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > openharmonise > rm > tasks > Scheduler


1 /*
2  * The contents of this file are subject to the
3  * Mozilla Public License Version 1.1 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at http://www.mozilla.org/MPL/
6  *
7  * Software distributed under the License is distributed on an "AS IS"
8  * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
9  * See the License for the specific language governing rights and
10  * limitations under the License.
11  *
12  * The Initial Developer of the Original Code is Simulacra Media Ltd.
13  * Portions created by Simulacra Media Ltd are Copyright (C) Simulacra Media Ltd, 2004.
14  *
15  * All Rights Reserved.
16  *
17  * Contributor(s):
18  */

19
20 package org.openharmonise.rm.tasks;
21
22 import java.io.*;
23 import java.util.*;
24 import java.util.Vector JavaDoc;
25 import java.util.logging.*;
26 import java.util.logging.Logger JavaDoc;
27
28 import org.openharmonise.commons.dsi.*;
29 import org.openharmonise.commons.net.*;
30 import org.openharmonise.rm.HarmoniseExceptionHandler;
31 import org.openharmonise.rm.config.ConfigSettings;
32
33
34
35 /**
36  * Handles the running of scheduled tasks.
37  *
38  * @author Michael Bell
39  * @version $Revision: 1.2 $
40  *
41  */

42 public class Scheduler implements Runnable JavaDoc {
43     static final String JavaDoc PNAME_SITE_URL = "SITE_URL";
44     static final String JavaDoc PNAME_SCHEDULE_PERIOD = "SCHEDULE_PERIOD";
45
46     /** Instance of this class
47      */

48     private static Scheduler m_instance = null;
49
50     /** Variable to control running of thread
51      */

52     private boolean m_bKeepRunning = true;
53
54     /** Interface to database
55      */

56     private AbstractDataStoreInterface m_dbinterf = null;
57
58     /** Counter for number of iterations
59      */

60     private int m_nCounter = 0;
61
62     /** Vector of Exceptions, for use in collecting info on running of tasks
63      */

64     private Vector JavaDoc m_Exceptions = null;
65
66     /**
67      * Vector containing ids of tasks that have thrown an exception, will not be run again and need fixing
68      */

69     private Vector JavaDoc m_RogueTasks = null;
70
71     /**
72      * Period, in seconds, of scheduler
73      */

74     private int m_schedule_period = 30*1000;
75     
76     /**
77      * Logger for this class
78      */

79     private static final Logger JavaDoc m_logger = Logger.getLogger(Scheduler.class.getName());
80
81     /**
82      * Contructs new Scheduler object
83      *
84      * @param dbinterf Interface to database
85      */

86     public Scheduler(AbstractDataStoreInterface dbinterf) {
87         m_dbinterf = dbinterf;
88     }
89
90     /* (non-Javadoc)
91      * @see java.lang.Runnable#run()
92      */

93     /**
94      * Run method. Executes pending tasks and updates next run time for each task.
95      */

96     public void run() {
97         m_bKeepRunning = true;
98         
99         while (m_bKeepRunning == true) {
100             int nTaskId = -1;
101
102             if(m_logger.isLoggable(Level.FINE)) {
103               m_logger.log(Level.FINE,"Checking tasks....");
104             }
105
106             try {
107                 List tasks = TaskCache.getInstance().getPendingTasks();
108                 
109                 for (Iterator iter = tasks.iterator(); iter.hasNext();) {
110                     Task tsk = (Task) iter.next();
111
112                     nTaskId = tsk.getId();
113
114                     if ((m_RogueTasks == null) ||
115                             (m_RogueTasks.contains(String.valueOf(nTaskId)) == false)) {
116                         tsk.execute();
117                         tsk.updateNextRuntime();
118                     }
119                 }
120
121                 Thread.sleep(m_schedule_period);
122                 m_nCounter++;
123             } catch (Exception JavaDoc e) {
124                 m_logger.log(Level.WARNING, e.getLocalizedMessage(), e);
125
126                 if (m_Exceptions == null) {
127                     m_Exceptions = new Vector JavaDoc(16);
128                     m_RogueTasks = new Vector JavaDoc(16);
129                 }
130
131                 m_Exceptions.add(
132                         new TaskExecutionException("Task id: " + nTaskId, e));
133
134                 m_RogueTasks.add(String.valueOf(nTaskId));
135
136                 try {
137                     HarmoniseExceptionHandler eHandler = new HarmoniseExceptionHandler();
138
139                     eHandler.setImportance(Email.IMPORTANCE_HIGH);
140
141                     eHandler.emailError(
142                             "TASK ERROR - TASK ERROR - TASK ERROR - TASK ERROR - TASK ERROR - URL:" +
143                             ConfigSettings.getProperty(PNAME_SITE_URL,
144                                                           "Not known"),
145                             eHandler.describeException(e), e);
146                 } catch (Exception JavaDoc e2) {
147                     m_logger.log(Level.WARNING, e2.getLocalizedMessage(), e2);
148                 }
149
150                 if (m_Exceptions.size() > 10) {
151                     m_bKeepRunning = false;
152                 }
153
154             }
155         }
156     }
157
158     /**
159      * Returns number of iterations complete so far
160      *
161      * @return number of interations
162      */

163     public int getCounterValue() {
164         return m_nCounter;
165     }
166
167     public void setPeriod(int nSeconds) {
168         this.m_schedule_period = nSeconds * 1000;
169     }
170
171     /**
172      * Returns an instance of scheduler. Fits singleton design pattern.
173      *
174      * @param dbinterf Interface to database
175      * @return instance of scheduler class
176      */

177     public static synchronized Scheduler instance(AbstractDataStoreInterface dbinterf) {
178         if (m_instance == null) {
179             m_instance = new Scheduler(dbinterf);
180
181             try {
182                 String JavaDoc sPeriod = ConfigSettings.getProperty(PNAME_SCHEDULE_PERIOD,
183                                                                "1");
184
185                 m_instance.setPeriod(Integer.parseInt(sPeriod));
186             } catch (Exception JavaDoc e) {
187                 //make do with the default period then
188
m_logger.log(Level.WARNING, e.getLocalizedMessage(), e);
189             }
190         }
191
192         return m_instance;
193     }
194
195     /**
196      * Test whether scheduler is running or not.
197      *
198      * @return is scheduler running
199      */

200     public boolean isRunning() {
201         return m_bKeepRunning;
202     }
203
204     /**
205      * Sets m_bKeepRunning to stop thread running.
206      */

207     public void stopRunning() {
208         m_bKeepRunning = false;
209     }
210
211     /**
212      * Returns Report on status of Scheduler, including list of exceptions thrown.
213      *
214      * @param bVerbose Has report to be verbose
215      * @return Status report
216      */

217     public String JavaDoc getStatusReport(boolean bVerbose) {
218         StringBuffer JavaDoc sBuf = new StringBuffer JavaDoc();
219
220         if (m_bKeepRunning) {
221             sBuf.append("<p>Scheduler running</p>");
222         } else {
223             sBuf.append("<p>Scheduler not running</p>");
224         }
225
226         sBuf.append("<p>No. of iterations:").append(m_nCounter).append("</p>");
227
228         if ((m_Exceptions == null) || (m_Exceptions.size() == 0)) {
229             sBuf.append("No Exceptions thrown.");
230         } else {
231             sBuf.append("<p>").append(m_Exceptions.size())
232                 .append(" Exceptions thrown.</p><hr>");
233
234             for (int i = 0; i < m_Exceptions.size(); i++) {
235                 sBuf.append("<p>")
236                     .append(((Exception JavaDoc) m_Exceptions.elementAt(i)).getMessage())
237                     .append("</p>");
238
239                 if (bVerbose) {
240                     String JavaDoc str = "";
241                     StringWriter swriter = new StringWriter();
242                     PrintWriter out = new PrintWriter(swriter);
243                     ((TaskExecutionException) m_Exceptions.elementAt(i)).printOriginalStackTrace(
244                             out);
245                     out.close();
246                     sBuf.append("<p>").append(swriter.toString())
247                         .append("</p>");
248                 }
249
250                 sBuf.append("<hr>");
251             }
252         }
253
254         return (sBuf.toString());
255     }
256
257     /**
258      * Clears list of exceptions thrown.
259      */

260     public void clearExceptionHistory() {
261         m_Exceptions.setSize(0);
262     }
263 }
Popular Tags