Search code examples
node.jsservicecronlong-running-processes

NodeJS Dynamic Service Loader & Runner


Context:

I'm trying to build a few slack hooks / notification services for a channel I'm active on, being the cheap-skate finance savvy person that I am, I'd like to make use of a free service as such (trail Heroku accounts, or similar products), thus I'd like to be able to run multiple services on a single instance.

I've created a generic runner, that should be based on a config and be able to pick up some node modules and supply them the config settings.

I'm using the following node_modules:

"auto-loader": "^0.2.0", "node-cron": "^1.2.0", "read-yaml": "^1.1.0"

config.yml

foo: 
  cron: 1 * * * *
  url: http://www.foo.com
  team: 
    - 
      slackId: bar
      bnetId: 1
      eloId: 1
    - 
      slackId: baz
      bnetId: 2
      eloId: 2

app.js

const autoLoader = require('auto-loader');
const readYaml = require('read-yaml');
const cron = require('node-cron');

const services = autoLoader.load(__dirname +'/services')

readYaml('config.yml', function(err, conf) {

    if (err) throw err;

    Object.keys(conf).forEach(function (key) {

        console.log('Creating CRON for ' + key);

        if(cron.validate(conf[key].cron)) {             

            console.log(conf[key].cron, '-> is valid cron');

            // the cron task below does not seem to fire ever
            cron.schedule(conf[key].cron, function(){
                services[key](conf[key]);
            });

        } else {
            console.log('Cron invalid for::' + key)
        }

    }); 
});

service/foo.js

module.exports = function (config) {
    console.log('foo entered!!');
    console.log(config)
}

Question:

What am I missing? If I remove the cron schedule, my services get hit, thus my assumptions are as follows...

Either I'm missing something conceptually about how long running process are meant to work in NodeJS (as this is my first), or I'm missing a super (not obvious) to me bug.

How do you create a long running task/process in NodeJS with separate scheduled code sections / tasks?


Solution

  • The code itself works as expected. The issue appears to be with the configuration of the cron.

    cron: 1 * * * * will run at 1 minute past the hour.

    cron: "*/1 * * * *"      # would run it every minute
    cron: "*/5 * * * *"      # would run it every 5 minutes
    cron: "*/10 * * * * *"   # would run every 10 seconds