I have a Google Cloud function that runs every 15 minutes.
However, I don’t want it to run every 15 mins. I just want it to run once. So I was suggested to use Google Cloud Tasks. However, I’m finding it difficult to implement the code.
So the whole thing is that a user from my Flutter app makes a post with the collection “ADS”. The collection has the following fields.
- string “PostStatus”
- timestamp “timeToStart”
- string “UID”, which is also equal to the document ID.
So I want that when the server time gets to “timeToStart”, the “status” should update to “Started” and that should be all. It shouldn’t run every 15 minutes as in my functions.
How do I use the Cloud Tasks to achieve this?
The function code
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
const database = admin.firestore();
const min = "*/5 * * * *";
exports.scheduled = functions.pubsub.schedule(min).onRun(async (context) => {
const batch = database.batch();
const {docs} = await database.collection("ADSGHANA").get();
docs.map((doc) => {
const {
UID,
timeToStart,
PostStatus,
} = doc.data();
const now = admin.firestore.Timestamp.now();
const starting = now > timeToStart
let val = PostStatus;
if (starting && PostStatus !== "Cancelled") val = "Started";
batch.update(
database.doc(`ADS/${doc.id}`), {
PostStatus: val,
},
);
await batch.commit();
});
4