user1732231
user1732231

Reputation:

Meteor: organising a loop on server side

How do I manage to run loops on server side of Meteor? e.g. I want to add something to database every 3 seconds.

for(var i = 0; i < 100; i++) {
    setInterval(Meteor.bindEnvironment(function() {
        post.type = types[getRandomInt(0,3)];
        post.message = 'sometext';
        post.timeCreated = new Date().valueOf();
        post.source = sources[getRandomInt(0,1)];

        Posts.insert(post);
        console.log('New post was added.');
    }, 1000));
}

but it doesnt make any sense: data generates very fast, without any delay.

Upvotes: 0

Views: 355

Answers (2)

Michel Floyd
Michel Floyd

Reputation: 20256

synced-cron is also a convenient package for running cron jobs on the server.

Upvotes: 0

Total Shaw
Total Shaw

Reputation: 503

Because you have something wrong in your understanding of setInterval, you could find how it works at here

As your code, you write setInterval in loop, which equals to call setInterval for 100 times. So 100 records would be inserted to your collection each time.

I could give you an example of insert record into Post per second at two ways.

PS: I prefer to use Meteor.setTimeout and other Meteor methods than Meteor.bindEnvironment

// First: only use setInterval
function insertPostsHandler(frequency) {
  var count = 0;
  // Meteor.setInterval would returns a handle
  // which can be used by Meteor.clearInterval to stop it
  var insertHandler = Meteor.setInterval(function() {
    if (count++ < frequency) {
      post.type = types[getRandomInt(0,3)];
      post.message = 'some text';
      post.timeCreated = new Date().valueOf();
      post.source = sources[getRandomInt(0,1)];

      Posts.insert(post);
      console.log('New post was added.');
    } else {
      // stop the timer when count >= frequency
      Meteor.clearInterval(insertHandler);
    }
  }, 1000);  // insert a record nearly per second
}


// Second: use setTimeout
function insertPostsHandler(frequency) {
  Meteor.setTimeout(insertPost, 1000, 0, frequency);
}
// You could also write directly, but I prefer to use a function holding it
// Because the code would be more clearly

// Meteor.setTimeout(insertPost, 1000, 0, frequency);

function insertPost(count, frequency) {
  if (count < frequency) {
    post.type = types[getRandomInt(0,3)];
    post.message = 'some text';
    post.timeCreated = new Date().valueOf();
    post.source = sources[getRandomInt(0,1)];

    Posts.insert(post);
    console.log('New post was added.');

    // call insertPost recursively when count < frequency
    setTimeout(insertPost, 1000, ++count, frequency);
  }
}

You could use either one of them to insert post record

I wish it could help :-)

Upvotes: 3

Related Questions