Menu

[r678]: / javaontracks / src / net / jot / scheduler / JOTScheduler.java  Maximize  Restore  History

Download this file

310 lines (284 with data), 10.2 kB

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
/*
------------------------------------
JavaOnTracks Thibaut Colar
tcolar-jot AT colar DOT net
Artistic Licence 2.0
http://www.javaontracks.net
------------------------------------
*/
package net.jot.scheduler;
import java.util.Calendar;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
import net.jot.logger.JOTLogger;
/**
* Generic scheduler, that can run scheduled task/items.
* any task can be registered into the scheduler using registerItem()
* Works like a cron mostly.
* It is started by JOT at startup (by JOTInitializer)
* Note that new jobs are looked for every minute, so the "granularity" is about 1 minute.
* @author thibautc
*
*/
public class JOTScheduler extends Thread
{
private static JOTScheduler instance=null;
private int lastMinute=-1;
private boolean stop=false;
private boolean done=false;
// Hashtables are synchronized so they are good here.
private Hashtable items=new Hashtable();
private Hashtable itemOptions=new Hashtable();
private Hashtable itemThreads=new Hashtable();
private Hashtable itemLastRun=new Hashtable();
private JOTScheduler()
{
}
public static JOTScheduler getInstance()
{
synchronized(JOTScheduler.class)
{
if(instance==null)
{
instance=new JOTScheduler();
}
}
return instance;
}
/**
* Shuts down the scheduler and release resources
* @throws Exception
*/
public void shutdown() throws Exception
{
JOTLogger.log(JOTLogger.INFO_LEVEL, JOTScheduler.class, "Scheduler shutdown");
stop=true;
while(! done)
{
Thread.sleep(10000);
}
//TODO: = what about child process (scheduled items cuurently running)
Enumeration e=itemThreads.elements();
while(e.hasMoreElements())
{
Vector v=(Vector)e.nextElement();
for(int i=0;i!=v.size();i++)
{
JOTLogger.log(JOTLogger.INFO_LEVEL, JOTScheduler.class, "Scheduler shutdown, killing subprocess.");
Thread t=(Thread)v.get(i);
t.interrupt();
//t.destroy();
t=null;
}
}
instance.interrupt();
//instance.finalize();
instance=null;
JOTLogger.log(JOTLogger.INFO_LEVEL, JOTScheduler.class, "Scheduler shutdown completed.");
}
/**
* Register an item(ie: a job) in the scheduler.
*
@param item
@param options
*/
public void registerItem(JOTScheduledItem item, JOTSchedulingOptions options)
{
String objectName=item.getClass().getName();
JOTLogger.log(JOTLogger.INFO_LEVEL, JOTScheduler.class, "Registering scheduled item: "+objectName);
if(items.get(objectName)!=null)
JOTLogger.log(JOTLogger.WARNING_LEVEL, JOTScheduler.class, " ! Duplicated scheduled item: "+objectName);
items.put(objectName,item);
itemOptions.put(objectName,options);
if(!options.isStartNow())
{
Calendar now=JOTClock.getNow();
itemLastRun.put(objectName,new Long(now.getTime().getTime()));
}
}
/**
* Unregisters a job from the sheculer, ie: remove it.
* @param item
*/
public void unregisterItem(JOTScheduledItem item)
{
String objectName=item.getClass().getName();
JOTLogger.log(JOTLogger.INFO_LEVEL, JOTScheduler.class, "Unregistering scheduled item: "+objectName);
items.remove(objectName);
itemOptions.remove(objectName);
}
/**
* Main scheduler loop.
* Once scheduler.start() is call, it should run forever.
*/
public void run()
{
try
{
JOTLogger.log(JOTLogger.INFO_LEVEL, JOTScheduler.class, "Scheduler started.");
while(!stop)
{
Calendar now=JOTClock.getNow();
int minute=now.get(Calendar.MINUTE);
if(minute!=lastMinute)
{
// start child thread to process potential tasks in the current minute.
new JOTSchedulerRunner(now).start();
lastMinute=minute;
}
sleep(5000);
}
}
catch(Exception e)
{
JOTLogger.logException(JOTLogger.ERROR_LEVEL, this, "Error in scheduler.", e);
}
done=true;
}
/**
* Inner class
* Individual "minute" cron runner, will process all scheduled items for the given "minute"
* @author thibautc
*
*/
private class JOTSchedulerRunner extends Thread
{
private Calendar now=null;
JOTSchedulerRunner(Calendar now)
{
this.now=now;
}
/**
* Loops through all the items/jobs and run them if their shedule matches the current time.
*/
public void run()
{
try
{
Enumeration keys=items.keys();
while(keys.hasMoreElements())
{
String key=(String)keys.nextElement();
JOTLogger.log(JOTLogger.CAT_MAIN,JOTLogger.DEBUG_LEVEL, JOTScheduler.class, "** Start Key: "+key);
JOTScheduledItem item=(JOTScheduledItem)items.get(key);
JOTSchedulingOptions options=(JOTSchedulingOptions)itemOptions.get(key);
Vector threads=(Vector)itemThreads.get(key);
if(threads==null)
{
threads=new Vector();
}
if(item!=null && options!=null)
{
boolean multipleAllowed=options.getThreadingScheme()==JOTSchedulingOptions.START_NEW_THREAD_IF_PREVIOUS_NOT_COMPLETED;
// in those case no need to bother any further
boolean shouldSkip=item.skipRun() || (! multipleAllowed && threads.size()>0);
if(shouldSkip)
{
if((options.isStartNow() && itemLastRun.get(key)==null) ||
item.forceRun() ||
isMatchingRunEvery(key, options) ||
isMatchingSchedule(options))
{
String reason=item.skipRun()?"Item told us to skip this scheduled run.":"item already running.";
JOTLogger.log(JOTLogger.CAT_MAIN,JOTLogger.DEBUG_LEVEL, JOTScheduler.class, "Scheduler: skipping item: "+item+" : "+reason);
}
}
if(!shouldSkip)
{
synchronized(this)
{
boolean run= (options.isStartNow() && itemLastRun.get(key)==null) ||
item.forceRun() ||
isMatchingRunEvery(key, options) ||
isMatchingSchedule(options)
;
if(run)
{
// saving lastrun stamp
itemLastRun.put(key,new Long(now.getTime().getTime()));
// starting scheduledItem in new Thread and saving in itemThread
// Note: thread will "remove itself" from itemThread once done.
JOTSchedulerItemThread thread=new JOTSchedulerItemThread(key,item);
threads.add(thread);
itemThreads.put(key,threads);
thread.start();
}
}
}
JOTLogger.log(JOTLogger.CAT_MAIN,JOTLogger.DEBUG_LEVEL, JOTScheduler.class, "** End Key: "+key);
}
}
}
catch(Exception e)
{
JOTLogger.logException(JOTLogger.CAT_MAIN,JOTLogger.ERROR_LEVEL, JOTScheduler.class, "Error in main scheduler thread: ",e);
}
}
// Compare "now" with lastrun to see if it's time to run again
private boolean isMatchingRunEvery(String key, JOTSchedulingOptions options)
{
long mn=options.getRunEvery();
Long lastRun=(Long)itemLastRun.get(key);
if(mn==-1)
{
return false;
}
long howLongAgo=now.getTime().getTime()-lastRun.longValue();
boolean result=lastRun!=null && howLongAgo>mn*60000;
return result;
}
// Compare "now" with the item schedule
private boolean isMatchingSchedule( JOTSchedulingOptions o)
{
boolean match=o.isScheduleEnabled()
&& (o.getRunAtMonth()==null || o.getRunAtMonth().contains(""+now.get(Calendar.MONTH)))
&& (o.getRunAtWeekDays()==null || o.getRunAtWeekDays().contains(""+now.get(Calendar.DAY_OF_WEEK)))
&&(o.getRunAtDays()==null || o.getRunAtDays().contains(""+now.get(Calendar.DAY_OF_MONTH)))
&& (o.getRunAtHours()==null || o.getRunAtHours().contains(""+now.get(Calendar.HOUR_OF_DAY)))
&& (o.getRunAtMinutes()==null || o.getRunAtMinutes().contains(""+now.get(Calendar.MINUTE)));
//JOTLogger.log(JOTLogger.CAT_MAIN,JOTLogger.INFO_LEVEL,JOTScheduler.class,"howlong: "+howLongAgo+" "+result);
return match;
}
}
/**
* This thread handles running a particular item/job
* @author thibautc
*
*/
private class JOTSchedulerItemThread extends Thread
{
private String name;
private JOTScheduledItem item;
JOTSchedulerItemThread(String name, JOTScheduledItem item)
{
this.name=name;
this.item=item;
}
/**
* Calls the actual item run() method.
*/
public void run()
{
try
{
long start=JOTClock.getCurrentTime();
JOTLogger.log(JOTLogger.INFO_LEVEL, JOTScheduler.class, "Starting scheduled item: "+name);
// running item
item.run();
item.runCompleted();
// done: removing myself from itemThread
Vector threads=(Vector)itemThreads.get(name);
threads.remove(this);
itemThreads.put(name,threads);
long end=JOTClock.getCurrentTime();
long time=end-start;
JOTLogger.log(JOTLogger.INFO_LEVEL, JOTScheduler.class, "Completed scheduled item: "+name+" in "+time+"ms.");
}
catch(Exception e)
{
JOTLogger.logException(JOTLogger.CAT_MAIN,JOTLogger.ERROR_LEVEL, JOTScheduler.class, "Error in scheduler item thread: ",e);
}
}
}
}
Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.