我们可以将递归与 AWS lambda 函数一起使用,它可以在 15 分钟的时间限制内停止执行并保存它停止的点吗?

can we use recursion with AWS lambda function that it stops execution within 15 minutes time limit and save the point at which it stopped?

  1. 跟踪 lambda 函数经过的时间,在 9-10 分钟停止。
  2. 保存它停止的点并继续直到任务完成
  3. 强制使用lambda函数

不确定您正在尝试什么,但请查看 AWS Step Functions 以更好地编排您的无服务器递归乐趣。 还要注意成本。

入门: https://aws.amazon.com/getting-started/hands-on/create-a-serverless-workflow-step-functions-lambda/

示例: https://docs.aws.amazon.com/step-functions/latest/dg/sample-project-transfer-data-sqs.html

我支持 John Rotenstein 的回应,他指出如果您以这种方式使用 lambda,您可能不应该使用 lambda。出于我自己的好奇心,我认为您要寻找的代码是以下几行(写在Node.JS)

let AWS = require('aws-sdk');
let functionName = 'YOUR_LAMBDA_FUNCTION_NAME'
let timeThreshholdInMillis = 5000 // 5 seconds

exports.handler = async (event, context, callback) => {
    let input = JSON.parse(event['foo']); // input from previous lambda, omitted try-catch for brevity
    let done // set this variable to true when your code is done

    let interval = setInterval(() => {
        if (done) callback(null, true)

        let remainingTime = context.get_remaining_time_in_millis();

        if (remainingTime < timeThreshholdInMillis) {
            // Going to restart
            clearInterval(interval);
            // save your progress (local or remote) to `input` variable
            let lambda = new AWS.Lambda();
            return lambda.invoke({
                FunctionName: functionName,
                Payload: JSON.stringify({ 'foo': input }) // Pass your progress here
            }, (err, data) => {
                // kill container
                if (err) callback(err)
                else callback(null, data)
            });
        }
    }, 1000);
}

编辑:一个例子

这是为了阐明 'passing progress' 如何在递归 lambda 中工作。

假设您想每秒递增一个变量 (+1),并且您想在 Lambda 中执行此操作。

吉文斯 我们将每 1000 毫秒将变量递增 1。 Lambda 将 运行 直到剩余时间小于 5000 毫秒。 Lambda 执行超时为 60,000 毫秒(1 分钟)。

Lambda 函数伪代码:

function async (event, context) {
    let counter = event.counter || 0

    setInterval(() => {
        if (context.get_remaining_time_in_millis() < 5000) {
             // start new lambda and pass `counter` variable
             // so it continues counting and we don't lose progress
             lambda.invoke({ payload: { counter } })
        } else {
            // Add 1 to the counter variable
            counter++
        }
    }, 1000)

}