Firebase Notification through Cloud Scheduler

64 views
Skip to first unread message

Shailesh Saraswat

unread,
Mar 13, 2020, 11:00:52 AM3/13/20
to Firebase Google Group
I am creating a cloud function which will trigger every hour(for a reminder) through cloud scheduler.
 
But whenever any data is entered on a realtime database node (the same node where i check the time to send notification), multiple notifications are sent instead of one.

Please let me know if I am missing something.

exports.paymentreminder = functions.pubsub.schedule('every 1 minutes')
         .timeZone('Asia/Calcutta')
         .onRun(async(context) => {
     
  console.log('This will be run every 1 hour!');

var currenttime = moment.tz('Asia/Kolkata').format('YYYY-MM-DD HH:00');

var onedayless_currenttime = moment.tz('Asia/Kolkata').subtract(24,"hours").format('YYYY-MM-DD HH:00');
var currentdatetime = Number(Date.parse(currenttime))
var ondaylesstime  = Number(Date.parse(onedayless_currenttime));
 

  const offlineroomKeys = admin.database().ref(`offline_roomKeys`);
  offlineroomKeys.orderByKey().on("value",function(snapshot){
  snapshot.forEach(function(child) {
        var offlinekey  = child.key;
  console.log('offline key '+offlinekey);
  const offlineroomKeys_depth2 = admin.database().ref(`offline_roomKeys/${offlinekey}/`);
       
        offlineroomKeys_depth2.orderByChild('reminderB').equalTo(currenttime)
        .once("value", function(snapshot2){    // get the device token of the user

       
          if(snapshot2.val()!=null){
          snapshot2.forEach(function(child2) {
            
          var customeroomkey = child2.key;
           
            var lastTxn = Number(child2.val().lastTxn);
            var remindertime = child2.val().reminderB;

            var timestamp_reminder  = Number(Date.parse(remindertime));


       
           if(timestamp_reminder===currentdatetime && remindertime!=''){
           
             var usernodekey = offlinekey;
             var recvrPh = child2.val().phone;
             var customername = child2.val().name;
             var roomKey = child2.val().offKey;


             var conversation_msgid = child2.val().roomKey;

             var pendingBal = child2.val().pendBal;
           var moneymsg = 'Collect money on following date '+remindertime;
             var message = {  'message': ''+moneymsg+'','custmrName':''+customername+'',
                                'reminderDate':''+remindertime+'',

                               };
       
            var data_body2 = JSON.stringify(message);
           
         
                  const usertoken = admin.database()
                                   .ref(`users_token/${usernodekey}/`).once('value')
                                   .then(function(snapshotuser){  // get the device token of the user
                  var device_token = snapshotuser.child("userToken").val();
                                    
                     
                              var payload = {
                                             'data':{
                                                     'title': ' '+recvrPh+'',
                                                     'body': 'Payment reminder',
                                                     'roomKey':''+roomKey+'',
                                                     'notificationType':'2',
                                                     'userKey':''+usernodekey+'',
                                                     'message' :''+data_body2+'',
                                                     'show_in_foreground': 'true',
                                                     'icon':"default",
                                                     'default_sound':'true',
                                                     'click_action':"com.lenviz.chitchatpay.activities.EntryScreen",
                                                
                                                         },

                                                 };

                             if(device_token!=''){
                                       return admin.messaging().sendToDevice(device_token, payload)
                                             .then(function(response) {
                                             
                                     console.log("Successfully sent message:", JSON.stringify(response));
                                 
                                             })
                                             .catch(function(error) {
                                                 console.log("Error sending message:", error);
                                                   });
                                                   }else{
                                                     console.log('device tocken not found');
                                                   }

                                             })
                                             .catch(function(error) {
                                               console.log("Error User Not found:", error);
                                             });


           }else if(ondaylesstime===timestamp_reminder && remindertime!=''){
             console.log('inside else for remove old reminder');
              var adaNameRef = admin.database().ref(`offline_roomKeys/${offlinekey}/${customeroomkey}`);
                 adaNameRef.update({ reminderB: '' });
               
                  console.log('reminder removed');
                
           }


          });
        }
    
    })

})

})

});

Kato Richardson

unread,
Mar 18, 2020, 1:05:51 PM3/18/20
to Firebase Google Group
Shailesh,

Given that you're running this on a schedule, you don't need a persistent subscription. Try once() instead of on()?

☼, Kato

--
You received this message because you are subscribed to the Google Groups "Firebase Google Group" group.
To unsubscribe from this group and stop receiving emails from it, send an email to firebase-tal...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/firebase-talk/5f6f4f3b-6083-4372-9641-13a0bbd985c5%40googlegroups.com.


--

Kato Richardson | Developer Programs Eng | kato...@google.com | 775-235-8398

Reply all
Reply to author
Forward
0 new messages