I need to create a cloud function that initiates a timer that calls another cloud function after X minutes. It should repeat this N times, unless it's told to stop before N has been reached. Is this possible? I have been reading that you can only set up timers using external cron jobs or an app engine? Is it possible to do what I'm wanting to do this way? Is there a cost associated with that?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
There is no functionality built into Cloud Functions for this. You'll have to build something on top of Cloud Functions.
- Start with a cron job that runs say every minute.
- Now build a callback queue in a database, e.g. the Firebase Realtime Database. Each item in the queue contains (at least) the URL of the Cloud Function that needs to be called, and the timestamp of when it needs to be called.
Every time you want to schedule a callback, write a task into the queue. E.g.
queueRef.push({ timestamp: Date.now() + 5*60*1000, url: "https://mycloudfunctionsurlwithoptionalparameters" });
The function triggered by the cron job checks the queue for items to be triggered before now:
queueRef.orderByChild("timestamp").endAt(Date.now()).once("value").then(function(snapshot) { snapshot.forEach(function(child) { var url = child.val().url; fetch(url).then(function() { queueRef.child(child.key).remove(); }); }); });
So this functions calls the URL (using
fetch
) that was specified, and if the call succeeds it deletes the entry from the queue.