gpt4 book ai didi

node.js - 如何从 Lambda 每 24 小时发送一次 SNS 消息?

转载 作者:太空宇宙 更新时间:2023-11-04 01:31:02 25 4
gpt4 key购买 nike

我是 Lambda 新手,正在尝试编写一个函数,该函数将每 24 小时通过 SNS 发送一封包含流体量的电子邮件。此 Lambda 函数由 IoT 规则触发,如果没有 24 小时限制,收件箱将被电子邮件淹没。在 CloudWatch 中,即使 email_sent 标志等于 1,看起来也正在发送电子邮件。所以这让我觉得我没有正确构造我的括号和方括号?有人发现这段代码有什么问题吗?


var email_sent = 0; //Flag to determine if the email has been sent in the last 24 hours
var starttime = new Date(); //Date & time when the script starts running

....

exports.handler = (event, context, callback) => {
console.log('Start time.', starttime);
console.log('Email Sent Flag.', email_sent);
console.log('Received event:', event.my_volume, ' mL Volume'); //Fluid volume
var miliseconds = new Date() - starttime; //Calculate the time that has passed
console.log('Miliseconds.', miliseconds);
console.log(miliseconds/1000 + " Seconds.");
if (miliseconds => 86,400,000) { //Has 24 hours passed?
email_sent = 0; //set the email flag back to zero if the time has passed
}
// create/get topic
if (email_sent == 0) { //if the email flag is not set, setup topic and send the email
createTopic('aws-iot-button-sns-topic', (err, topicArn) => {
if (err) {
return callback(err);
}
console.log(`Publishing to topic ${topicArn}`);
// publish message
const params = {
Message: `The fluid level is low on your system: ${event.my_volume} mL.`,
Subject: `Low Fluid Level Alert - Knight`,
TopicArn: topicArn,
};

// result will go to function callback
SNS.publish(params, callback);
console.log('SNS Published.');
email_sent = 1; // after email is sent, reset the flag
starttime = new Date(); // reset the starttime after the email is sent
}
);
}
};

谢谢

史蒂夫

最佳答案

因此,我认为有两件事应该采取不同的方式。

首先,你有这个:

createTopic('aws-iot-button-sns-topic', (err, topicArn) => {

现在你的函数正在创建不必要的主题而不删除它们,这是一个问题。您应该在外部创建 SNS 主题,并通过使用 Lambda 环境变量或对 SNS 主题 arn 进行硬编码来在此处引用它。或者,首先检查具有该名称的主题是否已存在,如果存在则不要创建它。

其次,Lambda 的运行时间不会超过 900 seconds (15 minutes) ,因此检查脚本是否已运行超过 24 小时是不可能的。

你应该做的是创建一个 CloudWatch event trigger that runs every 24 hours using cron 。这样,您的 lambda 将每 24 小时(或您配置的任何事件)运行一次,并且在代码中您只需发送一次消息即可。这样就无需检查现在是什么时间或您已发送了多少条消息,因为您知道事件触发器仅发生一次,因此您的消息将发送一次,并且您的 Lambda 会立即结束其执行。

Lambda 的本质是它们是短暂的且无状态的,因此请相应地设计您的服务:)

编辑:评论后,我对用例有了更多的了解...在这种情况下,Lambda 由 IoT 执行,我个人会将之前的执行时间存储在 SSM 参数存储或 DynamoDB 中,然后每当 Lambda 执行时,我都会获取该值,检查是否过了 24 小时,如果过了则发送 SNS。您必须这样做,因为否则 Lambda 将不知道上次执行时间是什么时候(并确保仅在成功的 SNS 发布调用时更新上次执行时间,即您确定当天发送了消息)

关于node.js - 如何从 Lambda 每 24 小时发送一次 SNS 消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56084618/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com