Skip to main content

How to run a scheduled job with EventBridge and Lambda

Greetings!

Triggering a piece of code by a timer has multiple use cases. Hence I am going to talk about how can we do it using AWS EventBridge.
  • Run daily/monthly reports
  • Send reminders
  • Scheduled data mining
  • Send marketing emails
The source code for this article can be found here.
Let's learn how we can achieve this architecture using AWS EventBridge and Lambada.

EventBridge

AWS EventBridge is a serverless event bus service that you can use to connect your applications with data from a variety of sources including AWS services and external services.

An event is an indicator of a change in the environment. When an event receives, it applies a rule to route the event to a target. Rules match events to targets based on either an event pattern or on a schedule which is the focus of this article.

Let's build the architecture using the serverless framework.

Initialize the project

Let's initialize the project using serverless cli.
mkdir eventbridge-lambda-trigger
cd eventbridge-lambda-trigger
serverless create --template aws-nodejs
npm init -y
We have installed the S3 dependency as well because we are going to use it to read the bucket.
Create a folder for our functions.
mkdir src
Enable the ES6 module as well in the package.json
{
  "name": "eventbridge-lambda-trigger",
  "version": "1.0.0",
  "author": "Manjula Jayawardana",
  "description": "Scheduled event trigger with EventBridge and Lambda",
  "main": "handler.js",
  "type": "module",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "license": "ISC"
}

Define the Lambda function

This is relatively simple for the example. Our Lambda function listens to EventBridge events on a fixed schedule. We only need to provide this information then the serverless framework creates the necessary rule and roles for us.
service: eventbridge-lambda-trigger
frameworkVersion: "3"

provider:
  name: aws
  runtime: nodejs16.x
  stage: dev
  region: us-east-1

functions:
  scheduledReport:
    handler: src/report-generator.handler
    events:
      - eventBridge:
          schedule: rate(2 minutes)

Let's write the Lambda function

We will log the request to the console. Hence this is a very simple function.
"use strict";

export const handler = async (event) => {
  console.log("Creating daily report....", event);
};
Go to CloudWatch and see the logs.

Conclusion

In this article, we have learned how to schedule an event using EventBridge and Lambda. By following best practices, we did it in infrastructure as code fashion using the serverless framework.

Happy learning ☺

References

https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-create-rule-schedule.html
https://www.serverless.com/framework/docs/providers/aws/events/event-bridge

Comments