Cloud Functions timer

2019-01-15 23:04发布

问题:

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.

  1. Start with a cron job that runs say every minute.
  2. 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.
  3. 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" });
    
  4. 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.