Home >Web Front-end >JS Tutorial >Schedule Events in EventBridge with Lambda

Schedule Events in EventBridge with Lambda

Linda Hamilton
Linda HamiltonOriginal
2024-12-20 01:36:11374browse

Schedule Events in EventBridge with Lambda

In this blog post, we'll explore how to schedule events using AWS EventBridge Scheduler and AWS Lambda. This method is efficient and scalable, ensuring your application can handle multiple scheduled events without creating a mess of individual EventBridge rules. Let's dive in!

What is AWS EventBridge?

AWS EventBridge is a serverless event bus service that makes it easy to connect applications using data from your own applications, integrated Software-as-a-Service (SaaS) applications, and AWS services. EventBridge delivers a stream of real-time data from event sources and routes that data to targets like AWS Lambda, Amazon SNS, and more.

What is AWS Lambda?

AWS Lambda is a serverless compute service that lets you run code without provisioning or managing servers. You can trigger Lambda functions directly from other AWS services, such as S3, DynamoDB, or EventBridge, and scale automatically from a few requests per day to thousands per second.

Prerequisites

Before we start, make sure you have the following:

  1. An AWS account
  2. Basic knowledge of Node.js
  3. AWS CLI configured on your machine

Step 1: Setting Up Your AWS Environment

Creating an IAM Role

Firstly, we need to create an IAM role that will allow AWS EventBridge Scheduler to invoke your Lambda function.

  1. Go to the IAM Console: Navigate to the IAM console, choose Roles from the left navigation pane, and click Create role.

  2. Select Trusted Entity: Choose AWS service, select Lambda, and click Next: Permissions.

  3. Attach Policies: Attach the following managed policies:

    • AWSLambdaBasicExecutionRole: Provides basic Lambda execution permissions.
    • AmazonEventBridgeSchedulerFullAccess: Allows EventBridge Scheduler to manage schedules.
  4. Review and Create: Provide a name for the role, e.g., LambdaExecutionRole, review the settings, and click Create role.

  5. Update Trust Relationship: After the role is created, go to the role details page. Under the Trust relationships tab, click Edit trust relationship. Update the trust policy to include scheduler.amazonaws.com service:

   {
     "Version": "2012-10-17",
     "Statement": [
       {
         "Effect": "Allow",
         "Principal": {
           "Service": "lambda.amazonaws.com"
         },
         "Action": "sts:AssumeRole"
       },
       {
         "Effect": "Allow",
         "Principal": {
           "Service": "scheduler.amazonaws.com"
         },
         "Action": "sts:AssumeRole"
       }
     ]
   }

Step 2: Creating the Lambda Function

We'll create a Lambda function that will process the scheduled events.

  1. Go to the Lambda Console: Navigate to the Lambda console, click Create function, and choose Author from scratch.

  2. Configure the Lambda Function: Set the function name to processScheduledEvent, select Node.js 16.x as the runtime, and use the existing role you created earlier (LambdaExecutionRole). Click Create function.

  3. Add Function Code: Replace the default code with your logic to process the event. For instance, you might log the event details or perform specific actions based on the event data:

   {
     "Version": "2012-10-17",
     "Statement": [
       {
         "Effect": "Allow",
         "Principal": {
           "Service": "lambda.amazonaws.com"
         },
         "Action": "sts:AssumeRole"
       },
       {
         "Effect": "Allow",
         "Principal": {
           "Service": "scheduler.amazonaws.com"
         },
         "Action": "sts:AssumeRole"
       }
     ]
   }
  1. Deploy the Function: Click Deploy to save the changes.

Step 3: Scheduling the Event

Now, let's write the code to schedule an event using AWS EventBridge Scheduler.

First, install the necessary AWS SDK modules:

   exports.handler = async (event) => {
     const eventDetails = event;

     // Your logic to process the event
     console.log("Processing scheduled event:", eventDetails);

     // Example: Process event
     // processEvent(eventDetails);

     return {
       statusCode: 200,
       body: JSON.stringify('Event processed successfully'),
     };
   };

Here’s a summary of the steps to implement the scheduling function:

Extract Event Details

Extract the event details from your application's input. Here is an example:

npm install @aws-sdk/client-scheduler @aws-sdk/client-lambda

Convert IST to UTC

Convert the scheduled time from IST (Indian Standard Time) to UTC (Coordinated Universal Time).

const eventDetails = {
  name: "TEST-EVENT-01",
  userId: "USER123",
  eventId: "EVENT-001",
  eventTime: '2024-12-17T18:05:00+05:30' // IST time in ISO format
};

Format the UTC Time String

Ensure the UTC time string is in the correct format required by EventBridge Scheduler (yyyy-MM-ddTHH:mm:ssZ).

const istTime = new Date(eventDetails.eventTime); // IST time
const utcTime = new Date(istTime.getTime() - 5.5 * 60 * 60 * 1000); // Convert to UTC

Create an EventBridge Schedule

Create an EventBridge schedule using the AWS SDK, specifying the Lambda function ARN as the target and including the event details as input.

const utcString = utcTime.toISOString().split('.')[0] + 'Z';

Conclusion

In this blog post, we walked through the process of setting up a scheduled event using AWS EventBridge Scheduler and Lambda. This approach ensures that our application can handle multiple scheduled events efficiently and scalably. With the power of AWS, you can build robust features that enhance user experience and streamline operations.

Happy coding!

The above is the detailed content of Schedule Events in EventBridge with Lambda. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn