Best way to set up polling of external API for each connected user


For as long as a user is connected to my app, I want to periodically (10-60 seconds) poll an external API for user specific data, and store the this in my database. Ther user is then subscribed to this data, which should reactively be updated every time new data comes in from the API.

Initially I had placed a setInterval(function fetchExternalResources() { inside an onCreated callback in the template, but it doesn’t feel right to put this on the client like this.

Is there perhaps a preferable approach?

Hi @tarlen,

You could use something like presences which monitors for connected users (and inserts them in the presences collection).

Then on the server, you can setup your timer:

var interval = 60 * 1000; // 60s
function myTask() {
  var userIds = presences.find({}, {userId: true}).map(function(p){ return p.userId});
  // do something for each user currently online
  Meteor.setTimeout(myTask, interval);
// Chain `setTimeout` instead of `setInterval` if your calls can be delayed (eg, HTTP calls).
Meteor.setTimeout(myTask, interval);

Or you can write something using collection.observe to create separate tasks for each user.

1 Like