云函数计时器 [英] Cloud Functions timer

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

问题描述

我需要创建一个云函数来启动一个计时器,该计时器在 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,它允许以编程方式安排调用 Cloud Functions 的任务.


    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天全站免登陆