【问题标题】:FCM - Timer function in node.jsFCM - node.js 中的计时器功能
【发布时间】:2017-12-08 11:38:48
【问题描述】:

这就是我制作 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 一无所知。

谢谢。

【问题讨论】:

  • Frede 的方法适用于短时间间隔。但是每种函数都有一个最大运行时间,setTimeout() 不能超过这个时间。另外:您将为您的功能“休眠”的整个时间付费。更有效的方法是使用外部计时器服务,例如 cron-job.org 或在 Google App Engine 上运行。见stackoverflow.com/questions/42790735/…

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


【解决方案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)

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 2019-08-04
    • 2018-09-08
    • 1970-01-01
    • 1970-01-01
    • 2013-03-23
    • 2019-10-20
    • 2022-10-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多