AWS Cloudwatch延迟触发Lambda功能

时间:2020-05-01 01:58:15

标签: amazon-web-services react-native aws-lambda expo amazon-cloudwatch

我正在使用Expo和RN开发一个用于在线广播的应用程序,用户可以在其中通知当前正在播放的节目。 我正在尝试使用与DynamoDB数据库连接的AWS Lambda函数将这些函数调度到Expo Push Notifications服务,并使用Cloudwatch在5分钟的间隔内运行该函数。

现在,在函数中,我发送通知,并在其正文中添加当前时间和当前播放的标题。然后,我设置了一个Cloudwatch规则,该规则每5分钟触发一次该功能。我希望以后会收到包含当前信息的通知,问题是在收到通知之前,我有5分钟的播放时间和标题。

我怀疑这是交通延迟还是什么原因,因为我每5分钟都会收到一则通知,但之前要通知5分钟。我尝试过创建具有相同结果的新规则。我尝试将cron表达式手动添加到计划中,但仍然得到相同的结果。

这是我在lambda函数中拥有的代码:

const https = require("https");
const AWS = require("aws-sdk");

const { Expo } = require('expo-server-sdk');
let expo = new Expo();

AWS.config.update({region: "us-east-2"});

let ddb = new AWS.DynamoDB({apiVersion: "2012-08-10"});

let retrieveParams = {
  TableName: "playing",
  Key: {
    "curr": {N: "1"}
  },
};

exports.handler = async (event) => {
    let dataString = '';
    let lastPlaying = "";
    let currPlaying = "";

    // Gets the latest played item
    ddb.getItem(retrieveParams, function(err, data) {
      if (err) {
        console.log("Error", err);
      } else {
        lastPlaying = data.Item.title.S;
      }
    });

    // Gets the currently playing title
    const response = await new Promise((resolve, reject) => {
        const req = https.get("http:serverurlsomethingsomething", function(res) {
          res.on('data', chunk => {
            dataString += chunk;
          });
          res.on('end', () => {
            resolve({
                statusCode: 200,
                body: JSON.parse(dataString)
            });
          });
        });

        req.on('error', (e) => {
          reject({
              statusCode: 500,
              body: 'Something went wrong!'
          });
        });
    });

    currPlaying = response.body.data[0].song;

    // Update the ddb if the current title has changed
    if (currPlaying !== lastPlaying) {
      // Updates the dynamoDB
      let newParams = {
        TableName: "playing",
        Item: {
          "curr": {N: "1"},
          "title": {S: currPlaying}
        }
      }; 

      ddb.putItem(newParams, function(err, data) {
        if (err) {
          console.log("Error", err);
        } else {
          console.log("Success", data);
        };
      });


      // Create the messages that you want to send to clents
      let messages = [];
      let somePushTokens = ["MyPhonesToken"]
      for (let pushToken of somePushTokens) {
        // Each push token looks like ExponentPushToken[xxxxxxxxxxxxxxxxxxxxxx]

        // Check that all your push tokens appear to be valid Expo push tokens
        if (!Expo.isExpoPushToken(pushToken)) {
          console.error(`Push token ${pushToken} is not a valid Expo push token`);
          continue;
        }

        // Construct a message (see https://docs.expo.io/versions/latest/guides/push-notifications)
        messages.push({
          to: pushToken,
          sound: 'default',
          body: `Minutes: ${new Date().getMinutes()} Seconds: ${new Date().getSeconds()} Title: ${currPlaying}`,
        })
      }

      let chunks = expo.chunkPushNotifications(messages);
      (async () => {
        // Send the chunks to the Expo push notification service. There are
        // different strategies you could use. A simple one is to send one chunk at a
        // time, which nicely spreads the load out over time:
        for (let chunk of chunks) {
          try {
            await expo.sendPushNotificationsAsync(chunk);
          } catch (error) {
            console.error(error);
          }
        }
      })();

      return "different";
    };

    return "same";
};

这是Cloudwatch规则的样子:

那么...有什么想法可能是问题吗?我想念什么吗?

P.D。是的...我将推送通知逻辑移到一个单独的文件中,以保持代码整洁。

0 个答案:

没有答案
相关问题