firebase cloud function run after 10 seconds

Viewed 84

I have a function similar to the one below. triggered when a user submits an application. looking for a suitable match with another user. If it doesn't find a match, I want it to check again after 10 seconds. I want it to call the function "deleteReference(gameid)". this function will also check again. the reference will be deleted if no other user has matched with it.

In some questions, they talk about a solution with a delay, but they are paid for the time they wait. How can I trigger the function I want after 10 seconds (by sending the gameID variable)? with the most affordable cost.

exports.myFunction = functions.database.ref('/match/{gameid}/').onCreate((snapshot, context) => {

    //do some processing here
    
    if (matchResult == true) {
        return null;
    } else {
        // HOW CAN I CALL THIS FUNCTION AFTER 10 SEC ?
        deleteReference(gameid)
        return null;
    }
});

function deleteReference(gameid) {
    //do some processing here

    if (matchResult == false) {
        database.ref("/match/").child(gameid).remove();
    }
}
1 Answers

One option is by using Cloud Task as linked by @samthecodingman. You could also use setTimeout() to delay the execution of the deleteReference() function. See sample code below:

exports.myFunction = functions.database.ref('/match/{gameid}/').onCreate((snapshot, context) => {

    //do some processing here
    
    if (matchResult == true) {
        return null;
    } else {
        // Execute the function after 10 seconds
        setTimeout(deleteReference(gameid), 10000)
        return null;
    }
});

function deleteReference(gameid) {
    //do some processing here

    if (matchResult == false) {
        database.ref("/match/").child(gameid).remove();
    }
}
Related