Prem
Prem

Reputation: 5987

How to publish randomized messages from zmq socket using setInterval?

The following code is written to simulate the zmq socket to send the hard-coded myData. How to make the setInterval function to send both myData & myData2 randomly? This will help me to simulate the messages from multiple sources (eg: services, IOT devices) to be published by same socket instance

var zmq = require('zmq');
var socket = zmq.socket('pub');

//simulated message
var myData = {
  "vmId" :  "abc",
  "vmName" : "myVm"
}
var myData2 = {
  "vmId" :  "xyz",
  "vmName" : "myVm_2"
}
socket.bindSync('tcp://localhost:3000');

setInterval(function(){
 socket.send(['notify_message', JSON.stringify(myData)]);
}, 1000);

Upvotes: 0

Views: 28

Answers (1)

rveerd
rveerd

Reputation: 4006

Use Math.random():

setInterval(function() {
  socket.send(['notify_message', 
   JSON.stringify(Math.random() < 0.5 ? myData : myData2)]);
}, 1000);

Upvotes: 1

Related Questions