executing a long running server method in meteor.js

20 Views Asked by At

I'm developing an app where :

  • the client clicks on a button to trigger a long running task on the server
  • the server executes the long running task and updates the task progression (lets say 10% every minute)
  • the client is updated at each server progression update

I was able to :

  • trigger the server method from the client
  • the server method does the task and updates the client
  • but I'm not able to stop the execution once the progression reaches 100% and the ui keeps forever updating the progression

This is my server method :

Meteor.methods({
'tasks.Create'() {


if (!this.userId) {
  throw new Meteor.Error('Not authorized.');
}

const id = TasksCollection.insert({
  progressionInPercentage:0,
  createdAt: new Date(),
  userId: this.userId,
});


Meteor.setInterval(()=>{const currentProgressionInPercentage = (ExportsCollection.findOne({_id:id})).progressionInPercentage
   ExportsCollection.update({_id:id},{$set:{progressionInPercentage:currentProgressionInPercentage + 5}})},1000)

   // can I use the clearInterval
  },
1

There are 1 best solutions below

0
Jankapunkt On

Meteor also provides a way to clear the interval via Meteor.clearInterval:

Meteor.methods({
  'tasks.Create' () {

    if (!this.userId) {
      throw new Meteor.Error('Not authorized.');
    }

    const id = TasksCollection.insert({
      progressionInPercentage: 0,
      createdAt: new Date(),
      userId: this.userId,
    });

    const intervalId = Meteor.setInterval(() => {
      const currentProgressionInPercentage = (ExportsCollection.findOne({ _id: id })).progressionInPercentage
      
      if (currentProgressionInPercentage >= 100) {
        return Meteor.clearInterval(intervalId)
      }
      
      ExportsCollection.update({ _id: id }, { $set: { progressionInPercentage: currentProgressionInPercentage + 5 } })
    }, 1000)
  }
})

Simply clear the interval, once percentage is equal or above 100 inside the interval handler function.

Resources: