DEV Community

Cover image for Schedule Events in EventBridge with Lambda
Ritul Singh
Ritul Singh

Posted on

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"
       }
     ]
   }
Enter fullscreen mode Exit fullscreen mode

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:

   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'),
     };
   };
Enter fullscreen mode Exit fullscreen mode
  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:

npm install @aws-sdk/client-scheduler @aws-sdk/client-lambda
Enter fullscreen mode Exit fullscreen mode

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:

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

Convert IST to UTC

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

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

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 utcString = utcTime.toISOString().split('.')[0] + 'Z';
Enter fullscreen mode Exit fullscreen mode

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 { SchedulerClient, CreateScheduleCommand } = require("@aws-sdk/client-scheduler");
const schedulerClient = new SchedulerClient({ region: "your-region" });

const createScheduleEventRequest = async (req, res) => {
  try {
    const scheduleParams = {
      Name: `schedule_event_${eventDetails.eventId}`,
      ScheduleExpression: `at(${utcString})`,
      Target: {
        Arn: 'arn:aws:lambda:your-region:your-account-id:function:processScheduledEvent', // Replace with your Lambda function ARN
        RoleArn: 'arn:aws:iam::your-account-id:role/LambdaExecutionRole', // Replace with your Role ARN
        Input: JSON.stringify(eventDetails)
      },
      FlexibleTimeWindow: { Mode: 'OFF' },
      State: 'ENABLED',
    };

    const scheduleResult = await schedulerClient.send(new CreateScheduleCommand(scheduleParams));
    console.log("EventBridge schedule created:", scheduleResult);

    return res.status(200).json({
      success: true,
      message: "Scheduled event created successfully",
    });
  } catch (error) {
    console.error("Error creating scheduled event:", error);
    return res.status(500).json({
      success: false,
      message: "Failed to create scheduled event",
      error: error.message,
    });
  }
};

module.exports = { createScheduleEventRequest };
Enter fullscreen mode Exit fullscreen mode

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!

Top comments (0)