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?
Asked
Active
Viewed 4,614 times
4
-
Do you need exactly x time later or x time +/- 10min. ( I have solution for a 10 or 15 min minus /plus time period) – Cappittall Feb 17 '18 at 19:12
-
Or there are some paid cron service that you may set a cron job with rest api. ie: https://www.setcronjob.com/documentation/api – Cappittall Feb 17 '18 at 19:23
1 Answers
6
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.
You might also want to have a look at Google Cloud Tasks, which allows programmatic scheduling of tasks that invoke Cloud Functions.

Frank van Puffelen
- 565,676
- 79
- 828
- 807
-
Isn't this only going to be called on every minute though? What if the timing changes half way though the minute? – Tometoyou Feb 18 '18 at 11:03
-
The maximum granularity depends on the cron service you use to trigger the function. For example `cron-job.org` can trigger up to 60 times per hour, so that is also the maximum granularity your queue can handle if you use this approach. – Frank van Puffelen Feb 19 '18 at 00:11