Search code examples
node.jsexpressrequestconsul

setInterval right away then wait 5 seconds


I am building a Node.js application and I have a setInterval function that runs every 5 seconds. My issue is the this function has to run before any of my routes will work in that file.

I need to run the setInterval right away upon my application starting but then run every 5 seconds after that.

So far I have tried setting the setInterval to a lower amount but that puts too much stress on my external service since this code format will be used in a bunch of files (~30).

var express = require('express');
var router = express.Router();
const config = require("../config/config");

const request = require("request");
var consul = require("consul")({host: '10.0.1.248'});
var consulBase = [];
var options;


setInterval(() => {
  consul.catalog.service.nodes('auth', function(err, results) {
    if(err) {console.log(err); throw err;}
    if(results.length <= 0) throw 'Unable to find any services with that name.. exiting process...';
    if(results.length > 0) consulBase = [];
    results.forEach((result) => {
      consulBase.push(result.ServiceAddress+ ':' +result.ServicePort);
    });
    var serviceURL = 'http://' + consulBase[Math.floor(Math.random()*consulBase.length)];
    options = {
      baseUrl : serviceURL
    };
  });
}, 5 * 1000);

router.get('/login', (req, res) => {
  request.get(req.path, options, (error, response, body) => {
    if (error) throw error;
    res.send(body);
  });
});


module.exports = router;

I'd be open to putting this in a different file and then having it present itself as a function that takes a service name and gives out an options variable with the data I need. Not sure how I would do that though.


Solution

  • You might want to look at scheduled tasks for node, using a package like node-cron. For example the following code will run every 5 seconds

    var cron = require('node-cron');
    
    yourCode();
    
    cron.schedule('*/5 * * * * *', () => {
      yourCode();
    });
    
    
    function yourCode(){
      console.log('running every 5 seconds');
    }
    

    Without node-cron

    yourCode();
    
    setInterval(() => {
      yourCode();
    }, 5 * 1000);
    
    
    function yourCode (){
      console.log('running every 5 seconds');
    }
    

    In seperate files

    //code.js
    module.exports.yourCode= (req, res) =>{
        console.log('running every 5 seconds');
    }
    
    //app.js
    const yourCode = require ('./code').yourCode;
    
    yourCode();
    
    setInterval(() => {
      yourCode ();
    }, 5 * 1000);