【问题标题】:Run FIrebase Cloud Function for more than 9 mins (540 sec)运行 FIrebase Cloud Function 超过 9 分钟(540 秒)
【发布时间】:2021-08-10 19:56:09
【问题描述】:

所以我在 firebase 函数中有一段异步(setInterval)代码。

export const auto_play = functions
  .runWith({ memory: "512MB", timeoutSeconds: 540 })
  .pubsub.schedule("*/15 * * * *")
  .onRun(async (context) => {

      const nums = polledDoc.data()?.nums as number[];
      setInterval(() => {
        const polledNum = nums.shift();
        // function suppose to run for atleast 10-15 mins coz nums.length can be any number from 60 to 90.
        // a function which save data to realtime database
        autoPollAlgo({ gameId: scheduledGame.docs[0].id, number: polledNum as number });
      }, 10 * 1000);
})

现在这段代码可以正常工作 3/5 次,但有时会在 num 数组完成之前从间隔中退出。有时它会在一分钟后停止,有时在 5 分钟后停止。

我知道函数的最大超时时间为 9 分钟,但是即使在 9 分钟之后,此异步代码如何工作。

经过一番挖掘后发现我没有返回任何承诺,因此该代码可以随时终止。现在为了让事情变得完美,我在块的末尾添加了一个承诺代码。

    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve(true);
     //to  make sure it exit after 15mins when interval code is done.
      }, 900000);
    });

现在发生了什么,函数在 9 分钟后(在 setinterval exec 的中间)结束了。它不会等待承诺解决。

我怎样才能保持函数以一致的方式运行异步任务 15 分钟?

【问题讨论】:

    标签: javascript firebase firebase-realtime-database google-cloud-functions


    【解决方案1】:

    在使用云功能苦苦挣扎之后,我提出了一个解决方案。 我将逻辑分为两个功能。 首先,我将nums 数组分成两半。

    我为一半的 num 执行了 setInterval,然后我使用 Cloud Pub/Sub 用另一半 num 执行另一个函数。

    
    // somewhere in first function
    pubSubClient.topic("play_half").publish(Buffer.from(JSON.stringify(restNum), "utf-8"), { gameId: scheduledGame.docs[0].id });
    
    export const auto_play_2 = functions
      .runWith({ memory: "512MB", timeoutSeconds: 540 })
      .pubsub.topic("play_half")
      .onPublish((message) => {
    
        const non_parse_arr = Buffer.from(message.data, "base64").toString();
       //other half nums
        const nums = JSON.parse(non_parse_arr);
       //...
    
    })
    
    

    【讨论】:

      猜你喜欢
      • 2017-08-30
      • 1970-01-01
      • 2021-09-17
      • 2018-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-02
      • 2015-06-19
      相关资源
      最近更新 更多