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:

JAVASCRIPT:

  1.  
  2. // Función hola();
  3. function hola() {
  4.    alert(“Hola”);
  5. }
  6.  
  7. // Tarea programada
  8. jsCron.set(“35 17 * * * hola()”);
  9.  

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:

JAVASCRIPT:

  1.  
  2. var jsCron = {
  3.                 items:[],
  4.                 interval: null,
  5.                 parse: function(strUnix) {
  6.                                 return strUnix.match(/^(d+|*) (d+|*) (d+|*) (d+|*) (d|*) +(w+)/);
  7.                 },
  8.                 check: function() {
  9.                                 var hoy = new Date();
  10.                                 var test = [new Date(), hoy.getMinutes(), hoy.getHours(), hoy.getDate(), hoy.getMonth(), hoy.getDay()];
  11.  
  12.                                 for (var i in this.items) {
  13.                                         var exec = 0;
  14.                                         var t = this.parse(this.items[i][1]);
  15.                                         for (var x in t)
  16.                                     if (t[x] && (t[x] == test[x] || t[x] == “*”))exec++;
  17.                                         if (exec == 5 && this.items[i][0] == 0) {
  18.                                                         eval(t[6]).call();
  19.                                                         this.items[i][0] = 1;
  20.                                         } else if (exec <5 && this.items[i][0] == 1) {
  21.                                                 this.items[i][0] = 0;
  22.                                         }
  23.                                 }
  24.                 },
  25.                 set: function(strUnix) {
  26.                         if (!/^(d+|*) (d+|*) (d+|*) (d+|*) (d|*) +(w+)/.test(strUnix)) return new Error(“Formato invalido”);
  27.                         this.items.push([0, strUnix]);
  28.                 },
  29.                 init: function(seg) {
  30.                         var seg = seg || 1000;
  31.                         this.interval = setInterval(“jsCron.check()”, seg);
  32.                 }
  33. };
  34. jsCron.init();
  35.  

Go to Source

  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • LinkedIn
  • Live
  • MySpace
  • Print
  • StumbleUpon
  • Technorati
  • YahooMyWeb
  • Yigg
*Name
*Mail
Website
Comment