Monday, January 12th, 2009
jsCron: Schedule code to run via simple JavaScript
Andrés Nieto has created a fun little JavaScript utility jsCron that lets you schedule JavaScript functions to run at certain times.
You would use it like this:
- // Función hola();
- function hola() {
- alert("Hola");
- }
- // Tarea programada
- jsCron.set("35 17 * * * hola()");
Of course, when doing this in a browser you aren’t to be sure on timing, if the page is running, etc…. so it is very different to server side cron jobs, but for simple time based alerts where you don’t want to do an Ajax check… nicely done.
The code is simple:
var jsCron = {
items:[],
interval: null,
parse: function(strUnix) {
return strUnix.match(/^(\d+|\*) (\d+|\*) (\d+|\*) (\d+|\*) (\d|\*) +(\w+)/);
},
check: function() {
var hoy = new Date();
var test = [new Date(), hoy.getMinutes(), hoy.getHours(), hoy.getDate(), hoy.getMonth(), hoy.getDay()];
for (var i in this.items) {
var exec = 0;
var t = this.parse(this.items[i][1]);
for (var x in t)
if (t[x] && (t[x] == test[x] || t[x] == “*”))exec++;
if (exec == 5 && this.items[i][0] == 0) {
eval(t[6]).call();
this.items[i][0] = 1;
} else if (exec < 5 && this.items[i][0] == 1) {
this.items[i][0] = 0;
}
}
},
set: function(strUnix) {
if (!/^(\d+|\*) (\d+|\*) (\d+|\*) (\d+|\*) (\d|\*) +(\w+)/.test(strUnix)) return new Error("Formato invalido");
this.items.push([0, strUnix]);
},
init: function(seg) {
var seg = seg || 1000;
this.interval = setInterval("jsCron.check()", seg);
}
};
jsCron.init();
[/javascript]





Why use eval and eval style setInterval. These methods are both slow and non working in for example an Air environment. So it can be done without evil evals.
Something like this would have been nicer:
jsCron.set(“35 17 * * *”, function() {
alert(“Yo!”);
});
Thx Spocke,
I change it and now you can use this method.
I may have missed that one. eval() does not work in Adobe Air applications?
@jaysmith
I’ve not actually tried it myself, but according to O’Reilly’s “Adobe AIR for JavaScript Developers Pocket Guide” eval() is “restricted within the application sandbox … Prohibited after onload. After the parsing time, you cannot use eval() to transform strings (such as those imported via XHR) into JavaScript code. The exception from this rule is eval() used with a string parameter of type JSON – pure JSON strings can be transformed into actual objects, although JSON code that contains call back functions are not supported.”
There’s a bunch of similar restrictions, e.g. document.write(), setTimeout() with a string parameter, and so on.
If it was possible to add a field for seconds I might use this.