所以我在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分钟之后工作的呢?
经过一番挖掘,我发现我没有返回任何承诺,所以这段代码可以随时终止。现在,为了让事情变得更完美,我在代码块的末尾添加了一个promise代码。
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(true);
//to make sure it exit after 15mins when interval code is done.
}, 900000);
});现在发生了什么,函数在9分钟后(在setinterval执行的中间)得到了一致的结束。它不会等待承诺来解决。
我如何保持一个函数能让异步任务持续运行15分钟?
发布于 2021-08-11 00:06:51
在苦苦挣扎于云函数之后,我提出了一个解决方案。我将逻辑划分为两个函数。首先,我将nums数组一分为二。
我执行了一半的数字的setInterval,然后我使用云发布/订阅来执行另一半数字的另一个函数。
// 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);
//...
})https://stackoverflow.com/questions/68732826
复制相似问题