Reputation: 853
I want to set up a timer inside my google cloud function. I have a database trigger on update. I have tried this method but it seemed to be not working.
const functions = require('firebase-functions');
exports.timer = functions.firestore
.document("/kullanici/{uid}")
.onUpdate((change,context) => {
const newfieldvalue = change.after.data();
const dolfieldvalue = change.before.data();
if(newfieldvalue.minebuildtime ===dolfieldvalue.minebuildtime){
let x= newfieldvalue.minebuildtime;
setTimeout(function(){
//do some database update here after x seconds;
},x);
}
return null;
});
Upvotes: 0
Views: 768
Reputation: 317342
This is not going to work the way you expect, because the Cloud Functions runtime will clamp down on resources after the function returns. Since the function returns immediately with null, that means Cloud Functions prevents the timer from triggering.
The only way you can get this time to work is if you return a promise that resolves only after the timer has finished executing, in addition to all other asynchronous work kicked off by the function.
Further complicating matters is the fact that, when a function times out (default 60s, configurable max 9 minutes), the timer will definitely never trigger.
All things considered, using setTimeout to set up a delayed execution is both error prone, and in some situations impossible. I would avoid it. If you happen to implement it correctly, be prepared for pay money for the time the function spends waiting around to complete the work.
If you want to delay the execution of some work in Cloud Functions, it's better to integrate with Cloud Tasks, which lets you defer to some work and invoke an HTTP function later.
Upvotes: 2
Reputation: 15246
When your Cloud Function returns from its top level, you can not assume that any further logic or processing will occur. This is documented at the section called Function execution timeline.
Upvotes: 2