Olarewaju Doyin Olarewaju Doyin - 11 months ago 68
Node.js Question

User scheduled jobs

I would like to allow my users set a schedule when they would like a particular action to occur. I use a node server on azure. I am currently looking at node-schedule and would be making use of it. What I am contemplating is running a master schedule every hour that checks the database for user specified schedules and this schedule sets a new schedule based on the schedules from users. But I don't know if this is a good practice, plus I'm concerned about the server load.

Answer Source

You can use node's cron for that, and accommodate in different ways. The pseudocode below gives a general idea.

var CronJob = require('cron').CronJob;

new CronJob('0 0 * * * *', function () { // every hour

   // check schedules planned for the future, stored as ISODate

     function(userSchedules) {
           userSchedules.forEach(sched) {

             // convert the date back to a string parsed by cron
             var d=extractDayHourMin(sched)
             var jobtime = d[4] +' '+d[3]+' '+d[2]+' '+d[1]+' '+d[0]

             // setup a new job
             var job=new CronJob(jobtime, function() {
                job.stop(); // fires only once

see https://github.com/ncb000gt/node-cron

However, this is possibly not the best solution : this does creates as much process as schedule, so yes, it would consume more resources than required. So instead of scheduling the schedulers, depending on the granularity of the possible calendar (hour, 1/2 hour, 1/4h), you could also query the db every hour (or 30 or 15mn) to retrieve every date that met, and trigger the appropriate function.