FCM - node.js中的定时器功能

时间:2017-12-08 11:38:48

标签: ios node.js firebase google-cloud-functions

这就是我使用firebase云功能发送静默推送通知的方式:

exports.sendSilentPyngNotification = functions.database.ref('/SNotification/{userid}').onWrite(event => {

const userid = event.params.userid
console.log('Start sending SILENT Notificaitons:-');

// Get the list of device notification tokens for the respective user
const getDeviceTokensPromise =  admin.database().ref(`/personal/${userid}/notificationTokens`).once('value');

// Get the user profile.
const getUserProfilePromise = admin.auth().getUser(userid);

return Promise.all([getDeviceTokensPromise, getUserProfilePromise]).then(results => {
const tokensSnapshot = results[0];
const user = results[1];

// Check if there are any device tokens.
if (!tokensSnapshot.hasChildren()) {
  return console.log('There are no notification tokens to send to.');
}

// Notification details.
const payload = {

  notification: {
    content_available : 'true'        
  },

  data : {
    senderid: 'Test',
    notificationtype: String(event.data.val().type)
  }

};

// Listing all tokens.
const tokens = Object.keys(tokensSnapshot.val());

// Send notifications to all tokens.
return admin.messaging().sendToDevice(tokens, payload).then(response => {
  // For each message check if there was an error.
  const tokensToRemove = [];
  response.results.forEach((result, index) => {
    const error = result.error;
    if (error) {
      console.error('Failure sending notification to', tokens[index], error);
      // Cleanup the tokens who are not registered anymore.
      if (error.code === 'messaging/invalid-registration-token' ||
          error.code === 'messaging/registration-token-not-registered') {
        tokensToRemove.push(tokensSnapshot.ref.child(tokens[index]).remove());
      }
    }
     console.log('Successfull sent SILENT NOTIFICATION');
  });
  return Promise.all(tokensToRemove);
});
});
});

问题:我想使用计时器反复触发此静默通知功能。我真的不知道如何在node.js中为这种函数编写计时器函数。

有人能快速指导我吗? 我是一名iOS开发人员,对node.js一无所知。

感谢。

1 个答案:

答案 0 :(得分:1)

您可能希望查看https://nodejs.org/en/docs/guides/timers-in-node/ 多次重复任何代码块的最简单方法是setInterval

// The function you want to fire multiple times
function functionToRepeat() {
    // Put your code here
}

// Calls functionToRepeat every 1500ms
var intervalObj = setInterval(functionToRepeat, 1500);

// To stop the interval 
clearInterval(intervalObj)

希望这有帮助!