倒计时结束后发送电子邮件

时间:2016-02-01 16:58:59

标签: javascript meteor countdown

我的CountDown遇到了问题。当计数器到期(t<=0)之前,我尝试向我在我的收藏中插入的某些人发送电子邮件。问题是,它只是在我访问该页面时被解雇。无论如何有可能服务器发送电子邮件甚至没有人在客户端?我希望我必须在服务器端构建一些东西?

      Template.decision.onRendered(function(){
         clearInterval(timeinterval);
         timeinterval = setInterval(function () {
         var endtime = '2016/02/10'     
          Meteor.call("getCurrentTime", function (error, result) {
            Session.set("time", result);
            var t = getTimeRemaining(endtime);
            Session.set("t", t);
          });
        }, 1000);
      });


  function getTimeRemaining(endtime){
    var t = Date.parse(endtime) - Session.get('time');
    var seconds = ("0" + Math.floor( (t/1000) % 60 )).slice(-2);
    var minutes = ("0" + Math.floor( (t/1000/60) % 60 )).slice(-2);
    var hours = ("0" + Math.floor( (t/(1000*60*60)) % 24 )).slice(-2);
    var days = Math.floor( t/(1000*60*60*24) );
    console.log(t);

    if(t <= 0 && timeinterval) {
      clearInterval(timeinterval);
      var to = Questions.findOne({_id:selectedDecisionId}).email;
      var questionText = Questions.findOne({_id:selectedDecisionId}).questionDB;
      var nameCreater = Questions.findOne({_id:selectedDecisionId}).name;
      Meteor.call('sendEmail',to,questionText,nameCreater);
    }

return {
  'total': t,
  'days': days,
  'hours': hours,
  'minutes': minutes,
  'seconds': seconds
};
}

在我的服务器上:

  Meteor.methods({
    'getCurrentTime': function (){
      return Date.parse(new Date());
    }
  });

2 个答案:

答案 0 :(得分:3)

更好的方法是在服务器上使用 cron job 。使用percolate:synced-cron包很容易做到这一点。

SyncedCron.add({
  name: 'Send emails',
  schedule: function(parser) {
    // parser is a later.parse object
    return parser.text('every 1 minute');
  },
  job: function() {
    // find relevant, expired documents
    // send an email to each user that is affected
  }
});

答案 1 :(得分:1)

var t = Date.parse(endtime) - Session.get('time');
if (globalTimer) {
    // clear existing timer, so when new user enters we "restart" countdown
    clearTimeout(globalTimer);
}
globalTimer = setTimeout(function(){
    // execute here whatever you want when the timer expires
}, t);