Timer.js
Summary
No overview generated for 'Timer.js'
var Timer = function() {
var timer = new java.util.Timer();
var tasks = new Array;
var state;
this.addTask = function(callback, args) {
var task = new Timer.Task(timer, callback, args);
tasks.push(task);
return task;
};
this.getTasks = function() {
return tasks;
};
this.purge = function() {
for (var i in tasks) {
if (tasks[i].state = Timer.Task.CANCELLED) {
delete tasks[i];
}
}
return timer.purge();
}
this.cancel = function() {
state = -1;
return timer.cancel();
};
this.valueOf = function() {
return timer;
};
this.toString = function() {
return "Timer " + timer + ((state == -1) ?
" (cancelled)" : " (tasks: " + tasks.length + ")");
};
return this;
};
Timer.Task = function(timer, callback, args) {
var task = new java.util.TimerTask({
run: function() {
if (state < Timer.Task.IDLE)
return;
cycles += 1;
state = Timer.Task.RUNNING;
app.debug("Running " + self);
try {
callback.apply(self, args);
} catch(exception) {
app.debug("Exception in " + self);
app.debug(exception.toSource());
self.cancel();
}
if (state > Timer.Task.IDLE)
state = Timer.Task.IDLE;
return;
}
});
var delay = 0, period = null;
var state = Timer.Task.IDLE;
var cycles = 0;
var self = this;
this.setDelay = function(d) {
d && (delay = d);
return;
};
this.setDate = this.setDelay;
this.setPeriod = function(p) {
period = p;
return;
};
this.run = function() {
try {
if (period === null) {
timer.schedule(task, delay);
} else {
timer.schedule(task, delay, period);
}
} catch(exception) {
app.log(exception);
if (exception.javaException.getClass() == java.lang.IllegalStateException) {
delete app.modules.task;
return new Task(callback, args, delay, period);
}
}
return;
};
this.cancel = function() {
app.debug("Cancelling " + self);
state = Timer.Task.CANCELLED;
return task.cancel();
};
this.cycles = function() {
return cycles;
};
this.lastRun = function() {
return new Date(task.scheduledExecutionTime());
};
this.state = function() {
return state;
};
this.valueOf = function() {
return task;
};
this.toString = function() {
return "Task " + task + ((state == Timer.Task.CANCELLED) ?
" (cancelled)" : " (cycle #" + cycles + ")");
};
return this;
};
Timer.Task.IDLE = 0;
Timer.Task.RUNNING = 1;
Timer.Task.CANCELLED = -1;
Documentation generated by
JSDoc on Sun Mar 4 00:51:24 2007