Tuesday 16 May 2017

Agenda not starting always on Node JS server

I have a small node app where I connect to a socket and when I receive the ok connection I want to start making request every 2 seconds to a web service and send the response via the socket. However, the Agenda app which schedules the jobs is not always starting the job. I think it might be related with the asynchronous style of node but I cannot spot what my error is

This is my code:

var express = require('express')
  , phoenix = require('phoenix-js')
  , app = express()
  , socket = new phoenix.Socket ( 'ws://the.socket.ip/socket' ,
    { transport: require ( 'websocket' ) .w3cwebsocket } )
  ,   request = require('request');
var Agenda = require('agenda');
function getMeterNames(){
  var fs = require('fs');
  var obj = JSON.parse(fs.readFileSync('./locals/meters.json', 'utf8'));
  return obj
}
var mongoConnectionString = "mongodb://127.0.0.1/agenda";
app.listen(4000, function(){
  console.log("Listening 4000...");
  // Connect socket
  socket.connect();
  // Fetch meter ips and ids from json.
  var meters = getMeterNames();
  console.log("meters");
  console.log(JSON.stringify(meters));
  // Create agenda.
  var agenda = new Agenda({db:{address: mongoConnectionString}});

  agenda.define('read_from_meter', {priority: 'high', concurrency: 10}, function(job, done) {
    var data = job.attrs.data;
    console.log("Sending from Meter ID:"+data.meterId+" url: "+data.url);
    request('http://google.com', function (error, response, body) {
      if (!error && response.statusCode == 200) {
        console.log("Url: "+data.url);
        console.log("Request Sent! "); // Print the google web page.
        done();
      }
      else{
        done();
      }
    })
  });

  function findMeterData(id){

    for(var i =0; i<meters.length; i++){
      if(id == meters[i].id){
        return meters[i];
      }
    }
    return false;
  }

  function startSendingData(ip,id,url){
    console.log("sending data-..."+ip+id+url);
    agenda.every('2 seconds', 'read_from_meter', {meterIp:ip, meterId:id, url: url});
    agenda.start();
    console.log("Agenda started..");
  }

  agenda.on('ready', function() {
    // Create channels for each meter
    var channels = [];
    for(var i =0; i<meters.length;i++){
      var meterId = meters[i].id;
      var meterIp = meters[i].ip;
      var url = 'http://'+meterIp+'/gas-level';
      var channelName = "room_meter:"+meterId;
      channel = socket.channel(channelName, {});
      channels.push(channel);
      // This will join the channel.
      channel.join().receive("ok", function (resp) {
        var connectedId = channel.topic.split(":")[1];
        meter = findMeterData(parseInt(connectedId));
        console.log("CONNECTED TO " + channelName);
        startSendingData(meter.id,meter.ip,'http://'+meter.ip+'/gas-level')
      }).receive("error", function (resp) {
        console.log("Unable to join", resp);
      });
    }

    //agenda.start();
  });

  function failGracefully() {
    console.log('Something is gonna blow up.');
    agenda.stop(() => process.exit(0));
  }

  process.on('SIGTERM', failGracefully);
  process.on('SIGINT', failGracefully);

When running the program I get the log Agenda started...

But after that the function defined on 'read_from_gas_meter' does not execute consistently. At random times I can see the logs, but most of the time I don't.

Can anyone help me out?



via Pablo Estrada

No comments:

Post a Comment