cronJobs I try to perform a method to restart all the values assigned to each user, every 6 hours but nothing happens


#1

help I just need the users who are registered with the role free then I need them according to the difference obtained from the subtraction if the two days went by then I command to reset everything again.

I’m trying to get results that at the moment of spending 6 hours all the parameters that each user has to restart
through cronJobs I also analyze if we say that 48 hours passed, then they are free roles

and restable the invitations

but it is not working for me, I do not know why, if someone could help me, I would be very grateful

timer2: function(timer) {
// try {
var sender = Meteor.users.aggregate([
{ $match: { roles:‘free’}}
])
if (!sender) {
return;
}

  for (var i = 0; i < sender.length; i++) {

      var result = Invitation.find({sender_id: sender[i]._id}).fetch();
      var data = ControlInvitaciones.find({}).fetch();
      var data_aceptadas = data[0].aceptadas;
      var data_enviadas = data[0].enviadas;
      var tiempo1 = data[0].tiempo;
      var tiempo2 = data[0].tiempo2;
      var tzone = sender[i].profile.timezone;
      var time_invitaciones = sender[i].profile.send_invitations_time;
      var roles = sender[i].roles;
      var time_invitaciones_aceptadas = sender[i].profile.AcceptCount_timer;
      //var date1 = momentT.tz(timer, tzone).format('YYYY-MM-DD HH:mm');
      var date1 = moment(timer, "YYYY-MM-DD HH:mm");
      var date2 = moment(time_invitaciones, "YYYY-MM-DD HH:mm");
      var resta = Math.abs(date2.diff(date1, 'hours'));
      var date3 = moment(time_invitaciones_aceptadas, "YYYY-MM-DD HH:mm");
      var restaAceptar = Math.abs(date3.diff(date1, 'hours'));

      if (resta !== NaN){
   

        if (resta >= 48 && sender[i].profile.send_invitations_check == true) {
          console.log("Tiempos restablecidos",sender[i]._id)
          Meteor.users.update({_id : sender[i]._id},{$set : {'profile.send_invitations_time' : "" ,'profile.send_invitations' : 0,'profile.send_invitations_check' : false}});
          var message = "You now have available Send Invitations";
          var type = "timer";
            var otro = "true"
          console.log('message',message)
          Meteor.call("resetTimerPush", sender[i]._id,message,type,otro, function(error, result){
            if(error){
              console.log("error", error);
            }
          });
      }
    
      if (restaAceptar >= 24 && sender[i].profile.accept_invitations_check == true) {
        console.log("Aceptar tiempos restablecidos")
        Meteor.users.update({_id : sender[i]._id},{$set : {'profile.AcceptCount_timer' : "" ,'profile.AcceptCount' : 0,'profile.accept_invitations_check' : false}});
        var message = "You now are available to Accept Invitations.";
        var type = "timer";
        var otro = "true"
          console.log('message',message)
        Meteor.call("resetTimerPush", sender[i]._id,message,type,otro, function(error, result){
          if(error){
            console.log("error", error);
          }
        });
    }

      }



  if (typeof (sender[i].profile.timerFree) == "undefined" || sender[i].profile.timerFree == ""){
     Meteor.users.update({_id : sender[i]._id},{$set : {'profile.timerFree' : new Date}});
     var timerFree = new Date
     console.log("update timerFree")
  }  else {
  
    var timerFree = sender[i].profile.timerFree;
    console.log("get profile timerFree")
  }

var fecha3 = moment(timer, "YYYY-MM-DD HH:mm");
var fecha4 = moment(timerFree, "YYYY-MM-DD HH:mm");
var resta2 = Math.abs(fecha4.diff(fecha3, 'hours'));
if (resta2 != NaN){
if (resta2 >= 6) {
 console.log("invitaciones removidas")
  var otro = "false"
 Invitation.remove({sender_id: sender[i]._id});
 Meteor.users.update({_id : sender[i]._id},{$set : {'profile.timerFree' : new Date}});
 var message = "Your matches and received activities have been reset";
 var type = "timer";
 Meteor.call("resetTimerPush", sender[i]._id,message,type,otro, function(error, result){
   if(error){
     console.log("error", error);
   }
 });

}
}

}
}


resetTimerPush: function(UserID,message,type,checkPush){
console.log(’---------------------------------------’);
console.log(’-------------resetTimerPush function------------’);
var user = Meteor.users.find({_id : UserID}).fetch();
var badge = user[0].profile.badge;
var tzone = user[0].profile.timezone;
var date1 = momentT.tz(new Date(), tzone).format(‘YYYY-MM-DD HH:mm’);
var emailData = {
name: user[0].profile.name,
lastname: user[0].profile.lastname,
enviado: date1,
message: message
};
if ( checkPush == ‘true’){
Email.send({
to:‘user@gmail.com’,
from: emailCliente,
subject: “WELCOME To findme”,
html: SSR.render(‘push-email’, emailData),
});
}

console.log('-----------------------------');
console.log('-------------RESET-------------');
console.log('------------------------------');
  Push.send({
    title : "Apps",
    text :  message,
    from : 'server',
    badge: badge,
    delayUntil: new Date(),
    payload:  {
          result: UserID,
          type : type
    },
    gcm:
    {
      image: 'https://apps.scalingo.io/findme_logo.png',
      style: 'inbox',
      summaryText: 'There are %n% notifications'
     },
     query: {
             userId: UserID
    },
});
},

#2

What are you using to process the cron jobs? Can you share that code?


#3

you mean, I do not understand

SyncedCron.add({
name: ‘reminder’,
schedule: function(parser) {

  return parser.text('every 1 minute');
},
job: function(intendedAt) {


Meteor.call('timer2', intendedAt); // test

}

});

Meteor.startup(function () {

SyncedCron.start();

});


#4

First, make sure SyncedCron is executing, then you’ll need to piece things back together, and finally, use es6 (let, const, not var), as you’ll keep scoping correctly.

Start by removing everything from the inner for loop (but keep the for loop), probably save a backup of your original code elsewhere and rewrite the function in pieces:

timer2:function(timer){
...
 if(!sender){return}
 for(let i = 0; i < sender.length; i++){
 // Leave everything here empty, except a console log
 console.log(`[Sender ${i}]: `, sender[i])
 }
}

Execute the above code in the cron job to see everything up to here works well.

Next, add the first block of data, where you only find data:

for(let i = 0; i < sender.length; i++){
 console.log(`[Sender ${i}]: `, sender[i])
      const result = Invitation.find({sender_id: sender[i]._id}).fetch();
      const data = ControlInvitaciones.find({}).fetch();
      const data_aceptadas = data[0].aceptadas;
      const data_enviadas = data[0].enviadas;
      ...
      let resta = Math.abs(....);
      let date3 = moment(time_invitaciones_aceptadas, "YYYY-MM-DD HH:mm");
      let restaAceptar = Math.abs(date3.diff(date1, 'hours'));
      console.log(`[Sender ${i}] - resta: `, resta);
 }

Use const whenever the variable will not be reassigned and let when you expect the variable to change.

Proceed with the same steps secuentially until you find the bug.


#5

in the local environment does not give any error, everything works fine like this code, but it happens when I upload it to the server does not work and I continue detailing I have noticed that I have thrown the following error

cron.js", “message”: "SyncedCron: Exception “reminder” MongoError: The’cursor’ option is required, except for aggregate with the explain argument

but it only happens on the server side.