【发布时间】:2020-09-04 19:51:07
【问题描述】:
我正在测试使用 IBM Cloud Functions(托管 Apache OpenWhisk)在操作完成后在后台运行代码,但我在调用 setTimeout 时提供的回调没有在正确的时间运行,而且它从未运行除非我第二次调用该函数。它在那个时候(晚)运行。
详情:
我想到了两个用例:
- 在内存中累积多个请求的数据,然后在大量累积或经过一定时间而没有请求时将大对象放入 Cloud Object Storage 存储桶。
- 为 API 管理每个容器的数据库连接,以便我可以关闭 IBM Cloud Functions 尚未终止的未使用容器中的连接。
我认为这会起作用,因为我使用了其他平台,例如 Google Cloud Run,我注意到在后台运行代码(使用 setTimeout 等),在请求完成后在 Stackdriver 中看到此代码的日志。而且,甚至还有一个由 AWS 开发倡导者创建的完整库,用于在 AWS Lambda 的后台管理 MySQL 连接 (https://www.npmjs.com/package/serverless-mysql)。
我测试了以下函数:
// from https://stackoverflow.com/questions/105034/how-to-create-guid-uuid
function uuidv4() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
function main() {
const runId = uuidv4().slice(31, 36);
console.log(`function started (runId = ${runId})`);
setTimeout(() => {
console.log(`after 5s delay (runId = ${runId})`);
}, 5000);
return {
msg: `ok (runId = ${runId})`,
};
}
我使用命令ibmcloud fn action update logging-in-background src/index.js --kind nodejs:10 部署它。
我创建了一个 LogDNA 实例并将其设置为我的平台实例,以便我的函数日志会转到它。这是我在使用命令ibmcloud fn action invoke logging-in-background --blocking 调用函数三次后在日志中看到的内容,每次间隔 10 秒(CRN 已编辑):
May 18 17:26:23 functions REDACTED 2020-05-18T21:26:23.956013Z stdout: function started (runId = 9be7c)
May 18 17:26:23 functions REDACTED Activation record '3589870e8ce44cc089870e8ce4acc018' for entity 'logging-in-background'
May 18 17:26:34 functions REDACTED 2020-05-18T21:26:34.111745Z stdout: after 5s delay (runId = 9be7c)
May 18 17:26:34 functions REDACTED 2020-05-18T21:26:34.115043Z stdout: function started (runId = faba6)
May 18 17:26:34 functions REDACTED Activation record 'ac47c067177648f187c0671776b8f1c2' for entity 'logging-in-background'
May 18 17:26:44 functions REDACTED 2020-05-18T21:26:44.248470Z stdout: after 5s delay (runId = faba6)
May 18 17:26:44 functions REDACTED 2020-05-18T21:26:44.253822Z stdout: function started (runId = 0af34)
May 18 17:26:44 functions REDACTED Activation record 'bbad3eabb3d64ab1ad3eabb3d61ab1a7' for entity 'logging-in-background'
您可以看到当我第一次调用该函数时,它只记录了“函数已启动”消息。 5 秒后它没有记录“延迟 5 秒后”消息。但随后,在第二次调用开始时,即第一次调用后 10 秒,它最终记录了与运行 9be7c 相关的“延迟 5 秒后”消息。 setTimeout 的回调似乎永远不会运行,直到最早在下次调用该操作时才会运行。
这是 Apache OpenWhisk 的设计方式,还是在操作完成后我没有正确地在后台运行代码?
【问题讨论】:
-
“Apache OpenWhisk 是这样设计的吗...” -- 您观察到并描述的是系统的预期工作方式。
标签: node.js ibm-cloud settimeout openwhisk ibm-cloud-functions