2017-12-08 5 views
1

でタイマー機能は、これは私がサイレントプッシュ通知を送信するためにfirebaseクラウド機能を作っています方法です:FCM - Node.jsの

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にタイマー機能を書く方法を全く考えていません。

誰でも素早くガイドできますか? 私はnode.jsを知らないiOS Devです。

ありがとうございました。あなたが任意のコードブロックを複数回繰り返すようにhttps://nodejs.org/en/docs/guides/timers-in-node/ 最も簡単な方法で見たいと思うかもしれません

+2

Fredeのアプローチは短い間隔で機能します。しかし、各タイプの関数には最大実行時間があり、 'setTimeout()'でそれを超えることはできません。また、あなたの機能が「眠っている」時間全体に対してお金を払うことになります。より効果的な方法は、cron-job.orgやGoogle App Engineで実行する外部タイマーサービスを使用することです。 https://stackoverflow.com/questions/42790735/cloud-functions-for-firebase-trigger-on-time –

答えて

1

は、このことができます

// 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) 

希望のsetIntervalです!

+0

よろしくおねがいします – user3804063