node.js - Where to store my node-schedules -


i'm new node/express , i'm making appointment system. want users make appointment day want , system sends them notification on exact time. found "node-schedule" module task don't know implemented this. there anyway store tasks in app.js or enough create node-schedule task every time hit end point example:

router.get('/', function(req, res, next) {  var j = schedule.schedulejob(date, function(){    send notification(); }); res.send(200); } 

note: not want run constant loop on sql table check dates

you'll need persist application data form of permanent storage either writing local files using sqlite, running own database server (like mongodb) or using cloud-based storage service amazon simpledb.

each of these options (and many others) have npm modules can use read/write/delete persistent data. examples, see mongodb, sqlite3, , simpledb, available using npm on npmjs.com.

update

per comment below: well, did ask store scheduled events. ;)

to persist scheduled events survive possible server failure, you'd need create storable data structure represent them , each event, create new instance of representation , store persistent storage (mysql).

typically, you'd use along lines of:

{   when:datetime        -- timestamp when event should fire   what:action          -- event should   args:arguments       -- arguments pass action   pending:boolean=true -- if false, event has fired } 

when initialize server, query persistent storage events pending===true , using results, initialize instances of node-schedule module.

when need schedule new event while server running, you'd create new event representation, write persistent storage , create new instance of node-schedule using it.

finally, and importantly customer happiness, when scheduled event completes successfully, before event handler (the action mentioned above) completes, need mark persistent version of event handling pending:false don't fire event more once.

so example:

  'use strict';    var scheduler = require('node-schedule');    /**    * storable representation of scheduled event    *    * @param {string|date} when    * @param {string}    * @param {array.<string>} [args=[]]    * @param {boolean} [pending=true]    *    * @property {date} persistentevent.when       - datetime event should fire.    * @property {string} persistentevent.what     - name of action run (must match key of persistentevent.actions)    * @property {array} persistentevent.args      - args pass action event handler.    * @property {boolean} persistentevent.pending - if true, event has not yet fired.    *    * @constructor    *    * @example    *    * var persistentevent = require('persistentevent'),    *     mysql = require('mysql'),    *     conn = mysql.createconnection({ ... });    *    * conn.connect();    *    * // @ point when initializing app...    *    * // assign persistent storage connection...    * persistentevent.setstore(conn);    *    * // load pending event persistent storage...    * persistentevent.loadall$(function (err) {    *   if (err) {    *     throw new error('failed load persistentevents: ' + err);    *   }    *    *   // point on, persistent events loaded , running.    *    * });    */   var persistentevent = function (when, what, args, pending) {     // initialize     persistentevent.cache.push(this.init({       when: when,       what: what,       args: args,       pending: pending     }));   };    // ==== persistentevent static methods ====    /**    * pre-defined action event handlers.    * <p>    * property key used match persistentevent.what property,    * , property value event handler function accepts optional    * array of args , callback (provided persistentevent.prototype.schedule)    * </p>    *    * @property {object}    * @property {function} actions.dosomething    * @property {function} actions.dosomethingelse    *    * @static    */   persistentevent.actions = {     dosomething: function (args, cb) {       // defaults       args = args || [];        // todo check specific args here ...        var result = true,           err = null;        // action here, possibly passed args        cb(err, result);     },     dosomethingelse: function (args, cb) {       // defaults       args = args || [];        // todo check specific args here ...        var result = true,           err = null;        // action here, possibly passed args        cb(err, result);     }   };    /**    * cache of persistentevents    *    * @type {array.<persistentevent>}    * @static    */   persistentevent.cache = [];    // data management    /**    * connection persistent storage.    * todo - should abstracted handle other engines mysql.    * @property {object}    * @static    */   persistentevent.storageconnection = null;    /**    * sets storage connection used persist events.    *    * @param {object} storageconnection    * @static    */   persistentevent.setstore = function (storageconnection) { // set persistent storage connection                                                             // todo - check args here...      // note: function isn't needed unless you're using other kinds of storage engines     // you'd want test engine used , mutate interface accordingly.      persistentevent.storageconnection = storageconnection;   };    /**    * saves persistentevent storageconnection.    *    * @param {persistentevent} event - event save    * @param {function} cb - callback on complete    * @static    */   persistentevent.save$ = function (event, cb) {     var conn = persistentevent.storageconnection;      if (null === conn) {       throw new error('requires storageconnection');     }      // todo - check active connection here...      // todo - check args here...      conn.query('insert table when = :when, = :what, args = :args, pending = :pending', event, cb);   };    /**    * loads persistentevents storageconnection.    * @param {function} cb -- callback on complete    * @static    */   persistentevent.loadall$ = function (cb) {     var conn = persistentevent.storageconnection;      if (null === conn) {       throw new error('requires storageconnection');     }      // check active connection here...      // check args here...      conn.query('query * table pending = true', function (err, results) {       if (err) {         return cb(err);       }       results.foreach(function (result) {         // todo: check existence of required fields here...         var event = new persistentevent(result.when, result.what, result.args, true);         event.schedule();       });       cb(null);     });   };    // ==== persistentevent methods ====    /**    * initialize instance of persistentevent.    *    * @param {object} opts    * @return {persistentevent}    */   event.prototype.init = function (opts) {     // check args     if ('object' !== typeof opts) {       throw new error('opts must object');     }      // set defaults     opts.args = opts.args || [];     opts.pending = opts.pending || true;      // convert string date, if required     if ('string' === typeof opts.when) {       opts.when = new date(opts.when);     }      // check opts contains needed properties     if (!opts.when instanceof date) {       throw new error('when must string representation of date or date object');     }      if ('string' !== typeof opts.what) {       throw new error('what must string containing action name');     }      if (!array.isarray(opts.args)) {       throw new error('args must array');     }      if ('boolean' !== typeof opts.pending) {       throw new error('pending must boolean');     }      // set our properties     var self = this;     object.keys(opts).foreach(function (key) {       if (opts.hasownproperty(key)) {         self = opts[key];       }     });      return this;   };    /**    * override object.tostring()    * @returns {string}    */   persistentevent.prototype.tostring = function () {     return json.stringify(this);   };    /**    * schedule event run.<br/>    * <em>side-effect: saves event persistent storage.</em>    */   persistentevent.prototype.schedule = function () {     var self = this,         handler = actions[this.what];      if ('function' !== typeof handler) {       throw new error('no handler found action:' + this.what);     }      persistentevent.save$(self, function () {       self._event = scheduler.schedulejob(self.when, function () {         handler(self.args, function (err, result) {           if (err) {             console.error('event ' + self + ' failed:' + err);           }           self.setcomplete();         });        });     });   };    /**    * sets event complete.<br/>    * <em>side-effect: saves event persistent storage.</em>    */   persistentevent.prototype.setcomplete = function () {     var self = this;     delete this._event;     this.pending = false;     persistentevent.save$(this, function (err) {       if (err) {         console.error('failed save event ' + self + ' :' + err);       }     });   }; 

note first-pass boilerplate show 1 way of designing solution problem. will require further effort on part run.


Comments

Popular posts from this blog

javascript - Bootstrap Popover: iOS Safari strange behaviour -

Website Login Issue developed in magento -

Can the constants be defined inside a model file of a framework in PHP? -