Reputation: 17996
I have the following CRON function inside my index.js file from my Cloud Functions:
// Starts the CRON every 5 minutes in order to get the latest sensors data
exports.cronFunction = functions
// .region('europe-west1')
.pubsub.schedule('2,7,12,17,22,27,32,37,42,47,52,57 * * * *')
.timeZone('Europe/Paris')
.onRun((context) => {
const day = moment();
const db = admin.database();
console.log('CRON Start for all orders!');
return updateStatsForDay(db, day, false, true).then(()=>{
return true;
}).catch(()=>{
return false;
});
});
The problem is that at specific times, the 5 minutes window is too short to finish running the script, so my question is: is there a way to skip the new execution if the previous one is still running?
Upvotes: 0
Views: 265
Reputation: 50930
All cloud functions instances are independent of each other and you cannot check if an instance is already active unless you keep track of them yourself. You can store a boolean value in realtime database and check that every time when a function triggers.
exports.cronFunction = functions
.pubsub.schedule('* * * * *')
.timeZone('Europe/Paris')
.onRun(async (context) => {
// Check if function is already running in database
const dbRef = admin.database().ref("_status/")
if ((await dbRef.once("value")).val().myFunction) return {error: "Function already running"}
// Else update the value to true
await dbRef.update({myFunction: true})
// Process the data
// Turn the value back to false
await dbRef.update({myFunction: false})
// Terminate the function
});
Upvotes: 1