cmii
cmii

Reputation: 3636

How to use scheduler for Firebase Cloud Functions with Realtime Database/Analytics triggers?

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:

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);
    });
}

Upvotes: 3

Views: 2085

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598817

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.

Upvotes: 1

Related Questions