问题
I'm working on a Firebase Cloud Function, to send triggered push notifications. Right now my function sends a push as soon as an user triggers the "IAP" event in my app.
'use strict';
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendIAPAnalytics = functions.analytics.event('IAP').onLog((event) => {
const user = event.user;
const uid = user.userId; // The user ID set via the setUserId API.
sendPushToUser();
return true;
});
function sendPushToUser(uid) {
// Fetching all the user's device tokens.
var ref = admin.database().ref(`/users/${uid}/tokens`);
return ref.once("value", function(snapshot){
const payload = {
notification: {
title: 'Hello',
body: 'Open the push'
}
};
console.log("sendPushToUser ready");
admin.messaging().sendToDevice(snapshot.val(), payload)
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
}
This functions works, push are sent and received.
I read some news about scheduling for Firebase Cloud Functions:
- https://medium.com/@pascalluther/scheduling-firebase-cloud-functions-with-cloud-scheduler-b5ec22ace683
- https://firebase.googleblog.com/2019/04/schedule-cloud-functions-firebase-cron.html
I understood, it's only for HTTP triggers ou PUB/SUB triggers. So for now it's always impossible to trigger functions with delays, by writing in realtime database or when analytics events are triggered.
Am I right? or is there a trick?
I read nothing about this.
EDIT: Official documentation https://firebase.google.com/docs/functions/schedule-functions
My syntax is wrong but I need something like this:
function sendPushToUser(uid) {
var ref = admin.database().ref(`/users/${uid}/tokens`);
return ref.once("value", function(snapshot){
const payload = {
notification: {
title: 'Hello',
body: 'Open the push'
}
};
functions.pubsub.schedule('at now + 10 mins').onRun((context) => {
admin.messaging().sendToDevice(snapshot.val(), payload)
})
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
}
回答1:
There is no built-in way to retrigger Cloud Functions with a delay. If you want such functionality you will have to build that yourself, for example by scheduling a function to run periodically and then see what tasks need to be triggered. See my answer here: Delay Google Cloud Function
As Doug commented, you can use Cloud Tasks to schedule individual invocations. You'd dynamically create the task, and then have it call a HTTP function.
来源:https://stackoverflow.com/questions/55956317/how-to-use-scheduler-for-firebase-cloud-functions-with-realtime-database-analyti