简体   繁体   English

如何在AWS Lambda函数中使用setInterval

[英]How to use setInterval in aws lambda function

I was experiencing difficulties when invoking same lambda function continuously by using setInterval function. 使用setInterval函数连续调用同一lambda函数时遇到了困难。

lambda function lambda函数

 var MongoClient = require('mongodb').MongoClient , format = require('util').format; function funUpdateCommand(event,context,callback){ var mongoUrl='mongodb://**.**.**.**:*****/DBname'; // var mongoUrl='mongodb://127.0.0.1:27017/DBname'; MongoClient.connect(mongoUrl, function(err, db) { if(err) throw err; var collection = db.collection('device'); var interval = setInterval(function() { collection.find({"deviceCommand.command":"getAudio","deviceCommand.timestamp":{ $lte: new Date((new Date)*1 - 60000*2)}}).toArray(function(err, results) { if(err){ console.log(err); }else{ for(var i=0;i<results.length;i++){ collection.update({_id:results[i]._id},{$set:{"deviceCommand.command":" "}},function(err, results) { }); } } }); }, 5000); }); context.succeed("Successfully uploaded"); } exports.handler=funUpdateCommand; 

I am trying to update some of the documents in my mongoDB,i need to run the aws lambda function as a continuous background job ,but when using setInterval it returns timeout error . 我正在尝试更新mongoDB中的某些文档,我需要将aws lambda函数作为连续的后台作业运行,但是当使用setInterval时,它将返回超时错误。

How can i continuously run my aws lambda function using setInterval? 如何使用setInterval连续运行AWS Lambda函数?

You can not keep lambda running forever. 您不能让lambda永远运行。 Lambda functions life time is limited with 300 seconds, after 300 seconds, your function dies. Lambda函数的生存时间限制为300秒,而300秒后,函数将死亡。 You can invoke same lambda function with cron expressions using CloudWatch Events. 您可以使用CloudWatch Events使用cron表达式调用相同的lambda函数。

You can learn more about lambda limits from here . 您可以从此处了解有关lambda限制的更多信息。

Without ruling out other potential connection issues and timeouts, it's worth discussing the fact that Lambda functions are not meant to run for long periods of time . 在不排除其他潜在的连接问题和超时的情况下,值得讨论的事实是Lambda函数不能长时间运行 Amazon have design the platform to be called on demand, and not to run like a micro-service or stay alive for a long time. 亚马逊已经设计了可以按需调用的平台,而不是像微服务那样运行或长时间存活。

You can read it from the horse's mouth here : 您可以从马的嘴读它在这里

Q: How long can an AWS Lambda function execute? 问:AWS Lambda函数可以执行多长时间?

All calls made to AWS Lambda must complete execution within 300 seconds. 所有对AWS Lambda的调用必须在300秒内完成执行。 The default timeout is 3 seconds, but you can set the timeout to any value between 1 and 300 seconds. 默认超时为3秒,但是您可以将超时设置为1到300秒之间的任何值。

You could schedule your function to run periodically, connect, do work, and disconnect. 您可以安排功能定期运行,连接,工作和断开连接。

@taskiner is correct. @taskiner是正确的。 CloudWatch doesn't support triggers more frequent than once per minute and Lambda is run length is limited to 300 seconds. CloudWatch不支持触发频率超过每分钟一次,Lambda的运行时间限制为300秒。 You do have a couple options though: 您确实有几个选择:

setTimeout: You could however configure CloudWatch to trigger your lambda every minute and then you could, based on the time use setTimeout to run your code at the next 30 second interval, repeat it once and then exit. setTimeout:但是,您可以将CloudWatch配置为每分钟触发一次lambda,然后您可以根据时间使用setTimeout在下一个30秒间隔运行代码,重复一次,然后退出。

Off the top of my head: 从我的头顶上:

var THRITY_SECONDS = 30000;

module.exports.handler = function(context, event, callback) {
    scheduleNext(runTask, function(){
            scheduleNext(runTask, callback);
    });
};

function scheduleNext(task, callback) {
    var now = new Date().getTime();
    var nextInterval = Math.ceil((new Date().getTime() / THIRTY_SECONDS) * THRITY_SECONDS);
    var delay - nextInterval - now;
     setTimeout(function() {
            task(callback);
    , delay);
}

function runTask(callback) {
    // your code executes here

    callback();
}

Just be advised that if the function runs for 40 seconds (starts at 1:01:20 PM, executes runTask at 1:01:30 and 1:02:00) you'll be charged for 30 seconds of compute time. 只是要注意,如果该功能40秒运行(在下午1时01分20秒开始,执行runTask在1:01:30和1时02分00秒),你会被收取的计算时间为30秒。 You'll have to do the cost analysis yourself and compare it with something like the cost of running a t2.micro instance (spot instances could help reduce the cost here). 您必须自己进行成本分析,并将其与运行t2.micro实例的成本进行比较(现货实例可以在此处帮助降低成本)。

External cron: Another option would be if you had server resources elsewhere that were stable you could have them run a cron job which uses the AWS CLI to trigger your function on the schedule you define. 外部cron:如果您在其他地方具有稳定的服务器资源,则可以使它们运行cron作业,该作业使用AWS CLI在定义的时间表上触发功能。

Of course if you're doing this, why not just run the task on said server? 当然,如果您要这样做,为什么不只在上述服务器上运行任务呢?

Event trigger Lambdas run on event triggers and there are several supported services that will trigger your lambda when data becomes available (s3 bucket/object changes, DynamoDB changes, etc). 事件触发器 Lambda在事件触发器上运行,并且有几种受支持的服务会在数据可用时(s3存储桶/对象更改,DynamoDB更改等)触发您的lambda。 Depending on your use case (looks like you are querying mongodb for new data to process) maybe you can write an event to DynamoDB and connect your lambda to the table's stream, or if you're saving your audio files to s3 then configure your lambda to listen for new files. 根据您的用例(看起来像您正在查询mongodb以获取要处理的新数据),您可以将事件写入DynamoDB并将lambda连接到表的流,或者如果将音频文件保存到s3,然后配置lambda监听新文件。 This is where you will see the cost benefits of using lambda because it will only run when there is work to do. 在这里,您将看到使用lambda的成本优势,因为它只会在有工作要做时运行。

I dont know how aws works but have you tried with a cron ? 我不知道aws的工作原理,但您尝试过cron吗? For example, this will launch YOURFUNCTION each hours, 例如,这将每小时启动一次YOURFUNCTION,

new CronJob("0 0 * * * *", YOURFUNCTION, null, true, 'America/Los_Angeles');

See https://www.npmjs.com/package/cron 参见https://www.npmjs.com/package/cron

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM