How to Setup Lambda Scheduled Events in AWS CDK

Creating scheduled events with EventBridge and Lambda functions with AWS Cloud Development Kit (CDK) allows you to run your functions regularly, similar to cron jobs in traditional servers.

This is perfect for daily data backups, regular data processing, cleanups, or any tasks you need to automate.

In this article, we’ll walk through how to set up a Lambda function and trigger it with scheduled events using CDK.

OG image showcasing a calendar with marked dates, a minimalist representation of AWS Lambda functions, and cron expressions, set against a digital, cloud computing-themed background with cool blues, whites, and greys.

Before we start, make sure you have the following installed:

  • AWS CLI
  • AWS CDK
  • Node.js

Setting Up Your CDK Project

If you don't have a CDK project, create a new CDK project by running the following in your terminal and in your new projects folder:

cdk init app --language typescript

Creating a Lambda Function

We will create a simple lambda setup to make sure we can test things are working.

Define a Lambda function in your CDK stack (lib/<your-stack-name>.ts):

import * as cdk from "aws-cdk-lib";
import { NodejsFunction } from "aws-cdk-lib/aws-lambda-nodejs";
import * as path from "path";
import { type Construct } from "constructs";
import * as lambda from "aws-cdk-lib/aws-lambda";

export class ArticlesStack extends cdk.Stack {
  constructor(scope: Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    const lambdaFn = new NodejsFunction(this, "TestLambda", {
      timeout: cdk.Duration.seconds(120),
      runtime: lambda.Runtime.NODEJS_20_X,
      entry: path.join(__dirname, "../lambdas/index.js"), // Path to the lambda
    });
  }
}

Then create a folder called lambdas and inside this create an index.js with your Lambda logic:

// lambdas/index.js
exports.handler = async function (event, context) {
  console.log("Lambda running");

  return {
    statusCode: 200,
    headers: { "Content-Type": "text/json" },
    body: "Hello world!",
  };
};

Now we should be able to see a successful response when monitoring our Lamda later.

Scheduling Your Lambda Function

We will be using EventBridge to manage our events. This is made easy thanks to CDK.

We need to create an event rule and attach our Lambda to it. Update your existing stack with the following:

import * as targets from "aws-cdk-lib/aws-events-targets";
import * as events from "aws-cdk-lib/aws-events";

// After defining your Lambda function...

// Schedule the Lambda function
const rule = new events.Rule(this, 'Rule', {
  schedule: events.Schedule.expression('cron(0 12 * * ? *)'), // Run at 12:00 PM UTC every day
});

rule.addTarget(new targets.LambdaFunction(lambdaFn));
// ...rest of file

To add your custom schedule, see this short tutorial on the AWS docs. It'll help you decrypt the Cron syntax.

And to make sure you didn't miss anything, here's the complete code for your stack:

export class ArticlesStack extends cdk.Stack {
  constructor(scope: Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    const lambdaFn = new NodejsFunction(this, "TestLambda", {
      timeout: cdk.Duration.seconds(120),
      runtime: lambda.Runtime.NODEJS_20_X,
      entry: path.join(__dirname, "../lambdas/index.js"), // Path to the lambda
    });

    // Schedule the Lambda function
    const rule = new events.Rule(this, "Rule", {
      schedule: events.Schedule.expression("cron(0 12 * * ? *)"), // Run at 12:00 PM UTC every day
    });

    rule.addTarget(new targets.LambdaFunction(lambdaFn));
  }
}

Deploying Your CDK Stack

Finally, deploy your CDK stack to AWS:

cdk deploy

Once it's up and running in your account, you should see the lambda being called at whatever schedule you set.

Don't forget to clean up afterward:

Cleanup Resources

If you only have a single stack to delete afterwards, you can delete the resources you have created by running:

cdk destroy

If you have multiple stacks, you will need to choose it by name:

cdk destroy <stack-name>

That's it!

You've now set up a Lambda function triggered by scheduled events using AWS CDK.

This setup enables you to automate tasks without manually triggering your functions.

Happy coding (and automating)!

AWSCDK
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses; Lead Developer, Software Architect, Product Manager, CTO and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.