

 [適用於 JavaScript 的 AWS SDK V3 API 參考指南](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/)詳細說明 第 3 版 適用於 JavaScript 的 AWS SDK (V3) 的所有 API 操作。

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 建立排程事件以執行 AWS Lambda 函數
<a name="scheduled-events-invoking-lambda-example"></a>

您可以使用 Amazon CloudWatch Event 建立叫用 AWS Lambda 函數的排程事件。您可以設定 CloudWatch Event 使用 Cron 表達式來排程何時叫用 Lambda 函數。例如，您可以排程 CloudWatch 事件，以在每個工作日叫用 Lambda 函數。

AWS Lambda 是一種運算服務，可讓您執行程式碼，而無需佈建或管理伺服器。您可以使用各種程式設計語言建立 Lambda 函數。如需 的詳細資訊 AWS Lambda，請參閱[什麼是 AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) 。

在本教學課程中，您會使用 Lambda JavaScript 執行時間 API 來建立 Lambda 函數。此範例會叫用不同的 AWS 服務來執行特定的使用案例。例如，假設組織傳送行動文字訊息給在一年週年紀念日恭喜他們的員工，如下圖所示。

![\[DynamoDB 表\]](http://docs.aws.amazon.com/zh_tw/sdk-for-javascript/v3/developer-guide/images/apigateway_example/picPhone.png)


此教學課程需約 20 分鐘完成。

本教學課程說明如何使用 JavaScript 邏輯來建立執行此使用案例的解決方案。例如，您將了解如何讀取資料庫，以判斷哪些員工已達到一週年的日期、如何處理資料，以及使用 Lambda 函數傳送文字訊息。然後，您將了解如何使用 Cron 表達式，在每個工作日叫用 Lambda 函數。

本 AWS 教學課程使用名為 Employee 的 Amazon DynamoDB 資料表，其中包含這些欄位。
+ **id** - 資料表的主索引鍵。
+ **firstName** - 員工的名字。
+ **電話** - 員工的電話號碼。
+ **startDate** - 員工的開始日期。

![\[DynamoDB 表\]](http://docs.aws.amazon.com/zh_tw/sdk-for-javascript/v3/developer-guide/images/apigateway_example/pic00.png)


**重要**  
完成成本：本文件中包含 AWS 的服務包含在 AWS 免費方案中。不過，在完成本教學課程後，請務必終止所有資源，以確保不會向您收費。

**若要建置應用程式：**

1. [完成先決條件 ](#scheduled-events-invoking-lambda-provision-resources)

1. [建立 AWS 資源 ](#scheduled-events-invoking-lambda-provision-resources)

1. [準備瀏覽器指令碼 ](#scheduled-events-invoking-lambda-browser-script)

1. [建立和上傳 Lambda 函數 ](#scheduled-events-invoking-lambda-browser-script)

1. [部署 Lambda 函數 ](#scheduled-events-invoking-lambda-deploy-function)

1. [執行應用程式](#scheduled-events-invoking-lambda-run)

1. [刪除資源](#scheduled-events-invoking-lambda-destroy)

## 先決條件任務
<a name="scheduled-events-invoking-lambda-prerequisites"></a>

若要設定和執行此範例，您必須先完成這些任務：
+ 設定專案環境以執行這些 Node.js TypeScript 範例，並安裝必要的 適用於 JavaScript 的 AWS SDK 和第三方模組。遵循[ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/cross-services/lex-bot/README.md) 上的指示。
+ 透過使用者登入資料建立共用組態檔。如需提供共用登入資料檔案的詳細資訊，請參閱 *AWS SDKs * [和工具參考指南中的共用組態和登入資料檔案](https://docs.aws.amazon.com/sdkref/latest/guide/file-format.html)。

## 建立 AWS 資源
<a name="scheduled-events-invoking-lambda-provision-resources"></a>

本教學課程需要下列資源。
+ 名為 **Employee** 的 Amazon DynamoDB 資料表，其索引鍵名為 **ID**，欄位如上圖所示。請務必輸入正確的資料，包括您要用來測試此使用案例的有效行動電話。如需詳細資訊，請參閱[建立資料表](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/getting-started-step-1.html)。
+ 具有連接許可的 IAM 角色，可執行 Lambda 函數。
+ 用於託管 Lambda 函數的 Amazon S3 儲存貯體。

您可以手動建立這些資源，但建議您 CloudFormation 如本教學所述，使用 佈建這些資源。

### 使用 建立 AWS 資源 CloudFormation
<a name="scheduled-events-invoking-lambda-resources-cli"></a>

CloudFormation 可讓您以可預測且重複的方式建立和佈建 AWS 基礎設施部署。如需 的詳細資訊 CloudFormation，請參閱[AWS CloudFormation 《 使用者指南》](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/)。

若要使用 建立 CloudFormation 堆疊 AWS CLI：

1. 在 [AWS CLI 使用者指南](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html)中安裝和設定 AWS CLI 下列指示。

1. 在專案資料夾的`setup.yaml`根目錄中建立名為 的檔案，並將 [ GitHub 上的此處](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/cross-services/lambda-scheduled-events/setup.yaml)內容複製到其中。
**注意**  
 CloudFormation 範本是使用 [ GitHub 上此處](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/resources/cdk/lambda_using_scheduled_events)提供的 AWS CDK 產生。如需 的詳細資訊 AWS CDK，請參閱 [AWS Cloud Development Kit (AWS CDK) 開發人員指南](https://docs.aws.amazon.com/cdk/latest/guide/)。

1. 從命令列執行下列命令，將 *STACK\$1NAME* 取代為堆疊的唯一名稱。
**重要**  
堆疊名稱在 AWS 區域和 AWS 帳戶中必須是唯一的。您最多可以指定 128 個字元，且允許使用數字和連字號。

   ```
   aws cloudformation create-stack --stack-name STACK_NAME --template-body file://setup.yaml --capabilities CAPABILITY_IAM
   ```

   如需`create-stack`命令參數的詳細資訊，請參閱 [AWS CLI 命令參考指南](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/create-stack.html)和 [CloudFormation 使用者指南](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-cli-creating-stack.html)。

   透過在 CloudFormation 儀表板上開啟堆疊，然後選擇資源索引標籤，在主控台中檢視**資源**清單。教學課程需要這些項目。

1. 建立堆疊時，請使用 適用於 JavaScript 的 AWS SDK 填入 DynamoDB 資料表，如 中所述[填入 DynamoDB 資料表](#scheduled-events-invoking-lambda-resources-create-table)。

### 填入 DynamoDB 資料表
<a name="scheduled-events-invoking-lambda-resources-create-table"></a>

若要填入資料表，請先建立名為 的目錄`libs`，並在其中建立名為 的檔案`dynamoClient.js`，並將以下內容貼入其中。

```
const { DynamoDBClient } = require( "@aws-sdk/client-dynamodb" );
// Set the AWS Region.
const REGION = "REGION"; // e.g. "us-east-1"
// Create an Amazon DynamoDB service client object.
const dynamoClient = new DynamoDBClient({region:REGION});
module.exports = { dynamoClient };
```

 此程式碼可在 [ GitHub 上取得](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/cross-services/lambda-scheduled-events/src/libs/dynamoClient.js)。

接著，`populate-table.js`在專案資料夾的根目錄中建立名為 的檔案，並將 [ GitHub 上的此處](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/cross-services/lambda-api-gateway/src/helper-functions/populate-table.js)內容複製到其中。對於其中一個項目，請將 `phone` 屬性的值取代為 E.164 格式的有效行動電話號碼，並將 的值`startDate`取代為今天的日期。

從命令列執行下列命令。

```
node populate-table.js
```

```
const {
BatchWriteItemCommand } = require( "aws-sdk/client-dynamodb" );
const {dynamoClient} = require(  "./libs/dynamoClient" );
// Set the parameters.
const params = {
  RequestItems: {
    Employees: [
      {
        PutRequest: {
          Item: {
            id: { N: "1" },
            firstName: { S: "Bob" },
            phone: { N: "155555555555654" },
            startDate: { S: "2019-12-20" },
          },
        },
      },
      {
        PutRequest: {
          Item: {
            id: { N: "2" },
            firstName: { S: "Xing" },
            phone: { N: "155555555555653" },
            startDate: { S: "2019-12-17" },
          },
        },
      },
      {
        PutRequest: {
          Item: {
            id: { N: "55" },
            firstName: { S: "Harriette" },
            phone: { N: "155555555555652" },
            startDate: { S: "2019-12-19" },
          },
        },
      },
    ],
  },
};

export const run = async () => {
  try {
    const data = await dbclient.send(new BatchWriteItemCommand(params));
    console.log("Success", data);
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```

 此程式碼可在 [ GitHub 上取得](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/cross-services/lambda-scheduled-events/src/helper-functions/populate-table.js)。

## 建立 AWS Lambda 函數
<a name="scheduled-events-invoking-lambda-browser-script"></a>

### 設定軟體開發套件
<a name="scheduled-events-invoking-lambda-configure-sdk"></a>

首先匯入 required 適用於 JavaScript 的 AWS SDK (v3) 模組和命令： `DynamoDBClient` 和 DynamoDB `ScanCommand`、 和 `SNSClient`以及 Amazon SNS `PublishCommand`命令。將 *REGION* 取代為 AWS 區域。然後計算今天的日期，並將其指派給參數。然後使用您在此範例的 [建立 AWS 資源](#scheduled-events-invoking-lambda-provision-resources)區段中建立的資料表名稱來建立 `ScanCommand`.Replace *TABLE\$1NAME* 的參數。

下列程式碼片段說明此步驟。(如需完整範例，請參閱[綁定 Lambda 函數](#scheduled-events-invoking-lambda-full)。)

```
"use strict";
// Load the required clients and commands.
const { DynamoDBClient, ScanCommand } = require("@aws-sdk/client-dynamodb");
const { SNSClient, PublishCommand } = require("@aws-sdk/client-sns");

//Set the AWS Region.
const REGION = "REGION"; //e.g. "us-east-1"

// Get today's date.
const today = new Date();
const dd = String(today.getDate()).padStart(2, "0");
const mm = String(today.getMonth() + 1).padStart(2, "0"); //January is 0!
const yyyy = today.getFullYear();
const date = yyyy + "-" + mm + "-" + dd;

// Set the parameters for the ScanCommand method.
const params = {
  // Specify which items in the results are returned.
  FilterExpression: "startDate = :topic",
  // Define the expression attribute value, which are substitutes for the values you want to compare.
  ExpressionAttributeValues: {
    ":topic": { S: date },
  },
  // Set the projection expression, which the the attributes that you want.
  ProjectionExpression: "firstName, phone",
  TableName: "TABLE_NAME",
};
```

### 掃描 DynamoDB 資料表
<a name="scheduled-events-invoking-lambda-scan-table"></a>

首先建立名為 的非同步/等待函數`sendText`，以使用 Amazon SNS 發佈文字訊息`PublishCommand`。然後，新增`try`區塊模式來掃描 DynamoDB 資料表，尋找今天工作週年紀念的員工，然後呼叫 `sendText`函數來傳送文字訊息給這些員工。如果發生錯誤，則會呼叫 `catch`區塊。

下列程式碼片段說明此步驟。(如需完整範例，請參閱[綁定 Lambda 函數](#scheduled-events-invoking-lambda-full)。)

```
exports.handler = async (event, context, callback) => {
  // Helper function to send message using Amazon SNS.
  async function sendText(textParams) {
    try {
      const data = await snsclient.send(new PublishCommand(textParams));
      console.log("Message sent");
    } catch (err) {
      console.log("Error, message not sent ", err);
    }
  }
  try {
    // Scan the table to check identify employees with work anniversary today.
    const data = await dbclient.send(new ScanCommand(params));
    data.Items.forEach(function (element, index, array) {
      const textParams = {
        PhoneNumber: element.phone.N,
        Message:
          "Hi " +
          element.firstName.S +
          "; congratulations on your work anniversary!",
      };
      // Send message using Amazon SNS.
      sendText(textParams);
    });
  } catch (err) {
    console.log("Error, could not scan table ", err);
  }
};
```

### 綁定 Lambda 函數
<a name="scheduled-events-invoking-lambda-full"></a>

本主題說明如何將此範例的 `mylambdafunction.js`和必要 適用於 JavaScript 的 AWS SDK 模組綁定到稱為 的綁定檔案中`index.js`。

1. 如果您尚未安裝，請遵循此範例[先決條件任務](#scheduled-events-invoking-lambda-prerequisites)的 來安裝 Webpack。
**注意**  
如需 *Webpack *的相關資訊，請參閱 [使用 Webpack 綁定應用程式](webpack.md)。

1. 在命令列中執行下列命令，將此範例的 JavaScript 綁定到名為 `<index.js>` 的檔案：

   ```
   webpack mylamdbafunction.js --mode development --target node --devtool false --output-library-target umd -o index.js
   ```
**重要**  
請注意，輸出名為 `index.js`。這是因為 Lambda 函數必須有`index.js`處理常式才能運作。

1. 將綁定輸出檔案 壓縮`index.js`為名為 的 ZIP 檔案`my-lambda-function.zip`。

1. `mylambdafunction.zip` 上傳至您在本教學[建立 AWS 資源](#scheduled-events-invoking-lambda-provision-resources)課程主題中建立的 Amazon S3 儲存貯體。

以下是 的完整瀏覽器指令碼程式碼`mylambdafunction.js`。

```
"use strict";
// Load the required clients and commands.
const { DynamoDBClient, ScanCommand } = require("@aws-sdk/client-dynamodb");
const { SNSClient, PublishCommand } = require("@aws-sdk/client-sns");

//Set the AWS Region.
const REGION = "REGION"; //e.g. "us-east-1"

// Get today's date.
const today = new Date();
const dd = String(today.getDate()).padStart(2, "0");
const mm = String(today.getMonth() + 1).padStart(2, "0"); //January is 0!
const yyyy = today.getFullYear();
const date = yyyy + "-" + mm + "-" + dd;

// Set the parameters for the ScanCommand method.
const params = {
  // Specify which items in the results are returned.
  FilterExpression: "startDate = :topic",
  // Define the expression attribute value, which are substitutes for the values you want to compare.
  ExpressionAttributeValues: {
    ":topic": { S: date },
  },
  // Set the projection expression, which the the attributes that you want.
  ProjectionExpression: "firstName, phone",
  TableName: "TABLE_NAME",
};

// Create the client service objects.
const dbclient = new DynamoDBClient({ region: REGION });
const snsclient = new SNSClient({ region: REGION });

exports.handler = async (event, context, callback) => {
  // Helper function to send message using Amazon SNS.
  async function sendText(textParams) {
    try {
      const data = await snsclient.send(new PublishCommand(textParams));
      console.log("Message sent");
    } catch (err) {
      console.log("Error, message not sent ", err);
    }
  }
  try {
    // Scan the table to check identify employees with work anniversary today.
    const data = await dbclient.send(new ScanCommand(params));
    data.Items.forEach(function (element, index, array) {
      const textParams = {
        PhoneNumber: element.phone.N,
        Message:
          "Hi " +
          element.firstName.S +
          "; congratulations on your work anniversary!",
      };
      // Send message using Amazon SNS.
      sendText(textParams);
    });
  } catch (err) {
    console.log("Error, could not scan table ", err);
  }
};
```

## 部署 Lambda 函數。
<a name="scheduled-events-invoking-lambda-deploy-function"></a>

在您專案的根目錄中，建立 `lambda-function-setup.js` 檔案，並將以下內容貼入其中。

將 *BUCKET\$1NAME* 取代為您上傳 Lambda 函數 ZIP 版本的 Amazon S3 儲存貯體名稱。以您 Lambda 函數的 ZIP 版本名稱取代 *ZIP\$1FILE\$1NAME*。將 *IAM\$1ROLE\$1ARN* 取代為您在本教學[建立 AWS 資源](#scheduled-events-invoking-lambda-provision-resources)課程中建立之 IAM 角色的 Amazon Resource Number (ARN)。將 *LAMBDA\$1FUNCTION\$1NAME* 取代為 Lambda 函數的名稱。

```
// Load the required Lambda client and commands.
const {
   CreateFunctionCommand,
} = require("@aws-sdk/client-lambda");
const {
   lambdaClient
} = require("..libs/lambdaClient.js");

// Instantiate an Lambda client service object.
const lambda = new LambdaClient({ region: REGION });

// Set the parameters.
const params = {
  Code: {
    S3Bucket: "BUCKET_NAME", // BUCKET_NAME
    S3Key: "ZIP_FILE_NAME", // ZIP_FILE_NAME
  },
  FunctionName: "LAMBDA_FUNCTION_NAME",
  Handler: "index.handler",
  Role: "IAM_ROLE_ARN", // IAM_ROLE_ARN; e.g., arn:aws:iam::650138640062:role/v3-lambda-tutorial-lambda-role
  Runtime: "nodejs12.x",
  Description:
    "Scans a DynamoDB table of employee details and using Amazon Simple Notification Services (Amazon SNS) to " +
    "send employees an email the each anniversary of their start-date.",
};

const run = async () => {
  try {
    const data = await lambda.send(new CreateFunctionCommand(params));
    console.log("Success", data); // successful response
  } catch (err) {
    console.log("Error", err); // an error occurred
  }
};
run();
```

在命令列中輸入以下內容以部署 Lambda 函數。

```
node lambda-function-setup.js
```

此程式碼範例可在 [ GitHub 上取得](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/cross-services/lambda-scheduled-events/src/helper-functions/lambda-function-setup.js)。

## 設定 CloudWatch 以叫用 Lambda 函數
<a name="scheduled-events-invoking-lambda-run"></a>

若要設定 CloudWatch 叫用 Lambda 函數：

1. 開啟 Lambda 主控台中的 **Functions (函數) 頁面**。

1. 選擇 Lambda 函數。

1. 在 **Designer (設計工具)** 下，選擇 **Add trigger (新增觸發)**。

1. 將觸發類型設定為 **CloudWatch Events/EventBridge**。

1. 針對規則，選擇**建立新規則**。

1.  填寫規則名稱和規則描述。

1. 針對規則類型，選取**排程表達**式。

1. 在**排程表達**式欄位中，輸入 Cron 表達式。例如，**cron(0 12 ？ \$1 MON-FRI \$1)**。

1. 選擇**新增**。
**注意**  
如需詳細資訊，請參閱[搭配使用 Lambda 與 CloudWatch Events](https://docs.aws.amazon.com/lambda/latest/dg/services-cloudwatchevents.html)。

## 刪除資源
<a name="scheduled-events-invoking-lambda-destroy"></a>

恭喜您！您已使用 透過 Amazon CloudWatch 排程事件叫用 Lambda 函數 適用於 JavaScript 的 AWS SDK。如本教學課程開頭所述，請務必在進行本教學課程時終止您建立的所有資源，以確保不會向您收費。您可以刪除在本教學[建立 AWS 資源](#scheduled-events-invoking-lambda-provision-resources)課程主題中建立的 CloudFormation 堆疊來執行此操作，如下所示：

1. 開啟 [CloudFormation 主控台]( https://console.aws.amazon.com/cloudformation/home)。

1. 在**堆疊**頁面上，選取堆疊。

1. 選擇**刪除**。