Skip to main content

Command Palette

Search for a command to run...

How to Use cron Jobs to Schedule Your Lambda Functions with AWS CDK

Published
5 min read
How to Use cron Jobs to Schedule Your Lambda Functions with AWS CDK
C

Fullstack Developer | Technical Writer | Freelancer 👩‍💻

Posts about Web Dev, Tech, and Entrepreneurship 📈

When building projects with AWS, there will come a time when you need to run things on a consistent and regular basis. A common example of this would be running a Lambda function once per day to perform some checks against a database. But, how do we achieve this outcome?

We could of course do it manually by triggering the Lambda function via the CLI or the dashboard but that’s going to get annoying very quickly and have potentially massive consequences if we miss a day. But, fortunately for us, we don’t need to do this because we can use a cron expression with an EventBridge rule to trigger our Lambda functions on a recurring basis automatically with no input from us.

Cron expressions are small expressions that refer to either a specific time or an interval time. For example, you could use the expression 5 4 * * * to refer to every day at 4.05 am. If you want to play around with cron expressions yourself and get a bit more familiar with them, you can use this website as a playground.

Building a cron-triggered Lambda Function

Now, we understand what cron expressions are as well as what they can help us achieve, let’s dive into the tutorial portion of this article and build a cron-triggered Lambda function ourselves using the AWS CDK and TypeScript.

Creating Our Lambda Function

The first step is to create our Lambda function which fortunately can be quite small as it’s just for testing purposes. So, inside your CDK project, create a new file at ./resources/lambdas/hello-world.ts, and inside that file, paste the below code.

export const handler = () => {
  console.log('hello world');
};

With the Lambda function’s code taken care of, let’s head over to our stack definition file where we’ll be defining our new Lambda function. So, inside your stack definition file inside the lib directory, paste the code below inside your constructor to define the Lambda function and add the below imports to the file.

import { NodejsFunction } from 'aws-cdk-lib/aws-lambda-nodejs';
import { Runtime } from 'aws-cdk-lib/aws-lambda';
import { Duration } from 'aws-cdk-lib';

// 👇 Defining our Lambda function
const helloWorldLambda = new NodejsFunction(this, 'HelloWorld', {
  runtime: Runtime.NODEJS_16_X,
  entry: './resources/lambdas/hello-world.ts',
  handler: 'handler',
  timeout: Duration.seconds(30),
});

And, that’s it! Our new Lambda function is defined and we can move on to defining and setting up the cron job trigger for it.

Defining A cron Job Trigger For Our Lambda Function

Thankfully, defining the cron trigger for our Lambda Function is easier than defining the Lambda function, all we need to do is add a new EventBridge rule with our cron schedule expression and then point the target of the rule to our new Lambda function. So, let’s take care of both of them now. Add the below imports to your file as well as the new definitions below your Lambda function definition.

import { Rule, Schedule } from 'aws-cdk-lib/aws-events';
import { LambdaFunction } from 'aws-cdk-lib/aws-events-targets';

// Your Lambda Function Definition

// 👇 Defining our CloudWatch Event Rule for our CRON job to run every 5 minutes
const rule = new Rule(this, 'Rule', {
  schedule: Schedule.cron({
    minute: '*/5',
  }),
});

// 👇 Defining our Lambda function as the target for our CloudWatch Event Rule
rule.addTarget(new LambdaFunction(helloWorldLambda));

After adding this code, we’ve defined everything we need to trigger our Lambda function using a cron expression. This Lambda function (once deployed) will be triggered every 5 minutes of every hour so for example would be triggered at 10.05, 10.10, 10.15, and so on. So, let’s deploy it and see it in action!

Deploying and Testing

To deploy your CDK stack, run the command cdk deploy in the root of your CDK project and then accept any prompts given to you by the terminal. Alternatively, you could pass the flag --require-approval never to the deploy command to skip the prompts but it can be helpful to review what is being deployed and/or destroyed before it happens.

After your deploy command has finished, head over to your AWS dashboard and then to Lambda where you should hopefully see your new function. Click on the new function and then head into the “Monitor” tab and then “Logs” to see all of the logs. If you now leave your Lambda function for 10/15 minutes it should run at least 2 times and you should see the logs individually listed on this page (you may need to refresh).

You can also click on the linked “LogStream” to see the logs in CloudWatch and the outputs of your Lambda functions. If you followed along with this tutorial, you should see Hello World logged out multiple times, if so it means everything is working as planned!

Once you’ve finished inspecting your logs and are finished with this tutorial, make sure to destroy your stack using the command cdk destroy to remove all the provisioned resources so you don’t get any unexpected bills.

Conclusion

With that, it’s brought us to the end of the tutorial! In this tutorial, we’ve covered why cron expressions are useful as well as how we can configure them to trigger a Lambda function on a schedule automatically for us using an EventBridge rule; all provisioned using the AWS CDK and TypeScript.

I hope you found this tutorial helpful and if you have any questions, feel free to reach out to me and I’ll be more than happy to help. Also, if you’d like to see the repository for this project, you can do so here.

And, until next time, thank you for reading!

R
Rakesh3y ago

did you tried to use EventBridge scheduler for job ? It's more flexible

1
C

I have done it previously with the EventBridge Scheduler and am planning on writing a separate blog post on using the scheduler for some more advanced use cases.

However, for something like scheduling a Lambda to run once per day at the same time or a recurring timeframe, I felt EventBridge Rules was a better fit because it's simpler to implement and also there are some restraints on the Scheduler still I believe:

  1. It's not fully implemented in the CDK so you'd need to use the SDK inside a Lambda function adding to the complexity
  2. It's only available in a small subset of regions where Rules are available in every region I believe.

Saying this I am still planning on doing a Scheduler post in the future, so keep an eye out for that. 😃

R
Rakesh3y ago

Coner Murphy Cool, thanks for your reply. check it out this blog post for EventBridge scheduler and CDK. I am not sure any specific constraint but this post may help you..

https://awsmantra.com/eventbridge-schedule-to-step-functions-no-codeno-lambda