0

I am trying to do something which i thought would have been very trivial, but apparently is not. I need to do something very simple, I need to run a setInterval so to check whether "today" is a new day, and if it is a new day, get some data and send an email.

Everytime i try, it returns me the usual issue Error: Meteor code must always run within a Fiber. Try wrapping callbacks that you pass to non-Meteor libraries with Meteor.bindEnvironment. The code is running on Meteor server in a Meteor startup function. All help will be greatly appreciated, i tried to solve it with async, fibers and future and i am either doing it wrong or i haven't found the answer yet. Thank you, Alessio

setInterval(function(){
    var now = moment().format('L');
    var date1 = new Date(now);
    var date2 = new Date(yesterday);
    var timeDiff = Math.abs(date2.getTime() - date1.getTime());
    var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
    if(diffDays>0){


        yesterday=now;

        //this is the part giving me problems
         Email.send({
        to: 'alexbonti83@hotmail.com',
        from: 'alexbonti83@hotmail.com',
        subject: 'test',
        text: 'test'
        });



    }else{
       // console.log('is the same day');
    }

},delay);

1 Answers1

1

If I may make a suggestion, you are better off running code like this through a backend cron job then through a setInterval. If your server is disrupted or restarts for any reason, the interval will be lost from memory and you are not going to get the expected behavior sending emails.

The package I use and like for this purpose is percolate studio's synced-cron: https://atmospherejs.com/percolate/synced-cron

The answer to why setInterval is not working in your case is addressed in the Meteor documentation:

Timers

Meteor uses global environment variables to keep track of things like the current request's user. To make sure these variables have the right values, you need to use Meteor.setTimeout instead of setTimeout and Meteor.setInterval instead of setInterval.

These functions work just like their native JavaScript equivalents. If you call the native function, you'll get an error stating that Meteor code must always run within a Fiber, and advising to use Meteor.bindEnvironment.

Jeremy S.
  • 4,599
  • 3
  • 18
  • 25