【发布时间】: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