云功能计时器 [英] Cloud Functions timer

查看:58
本文介绍了云功能计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个云功能,该功能可以启动计时器,并在X分钟后调用另一个云功能.除非被告知在达到N之前停止,否则它应该重复N次.这可能吗?我一直在读,您只能使用外部cron作业或应用程序引擎设置计时器?这样可以做我想做的事吗?有相关的费用吗?

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?

推荐答案

Cloud Functions中没有为此内置的功能.您必须在Cloud Functions之上构建一些东西.

There is no functionality built into Cloud Functions for this. You'll have to build something on top of Cloud Functions.

  1. cron作业开始,该作业每分钟运行一次.
  2. 现在在数据库中建立一个回调队列,例如Firebase实时数据库.队列中的每个项目(至少)包含需要调用的Cloud Function的URL,以及何时需要调用它的时间戳.
  3. 每次您要安排回调时,都将一个任务写入队列.例如

  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" });

  • cron作业触发的功能检查队列中是否有现在要触发的项目:

  • 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();
        });
      });
    });
    

    因此,此函数将调用指定的URL(使用fetch),如果调用成功,它将从队列中删除该条目.

    So this functions calls the URL (using fetch) that was specified, and if the call succeeds it deletes the entry from the queue.


    您可能还想看看 Google Cloud Tasks ,它可以通过编程方式对调用云功能的任务.


    You might also want to have a look at Google Cloud Tasks, which allows programmatic scheduling of tasks that invoke Cloud Functions.

    这篇关于云功能计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆