EventBridgeAWSLambda | 5 Min Read

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

Learn how to automate recurring Lambda functions using cron expressions and EventBridge rules with the AWS CDK and TypeScript.

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.

resources/lambdas/hello-world.ts
1export const handler = () => {
2 console.log('hello world');
3};
ts

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.

lib/stack.ts
1import { NodejsFunction } from 'aws-cdk-lib/aws-lambda-nodejs';
2import { Runtime } from 'aws-cdk-lib/aws-lambda';
3import { Duration } from 'aws-cdk-lib';
4
5// 👇 Defining our Lambda function
6const helloWorldLambda = new NodejsFunction(this, 'HelloWorld', {
7 runtime: Runtime.NODEJS_16_X,
8 entry: './resources/lambdas/hello-world.ts',
9 handler: 'handler',
10 timeout: Duration.seconds(30),
11});
ts

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.

lib/stack.ts
1import { Rule, Schedule } from 'aws-cdk-lib/aws-events';
2import { LambdaFunction } from 'aws-cdk-lib/aws-events-targets';
3
4// Your Lambda Function Definition
5
6// 👇 Defining our CloudWatch Event Rule for our CRON job to run every 5 minutes
7const rule = new Rule(this, 'Rule', {
8 schedule: Schedule.cron({
9 minute: '*/5',
10 }),
11});
12
13// 👇 Defining our Lambda function as the target for our CloudWatch Event Rule
14rule.addTarget(new LambdaFunction(helloWorldLambda));
ts

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!



Content

Latest Blog Posts

Below is my latest blog post and a link to all of my posts.

View All Posts

Content

Latest Video

Here is my YouTube Channel and latest video for your enjoyment.

View All Videos
AWS Bedrock Text and Image Generation Tutorial (AWS SDK)

AWS Bedrock Text and Image Generation Tutorial (AWS SDK)

Contact

Join My Newsletter

Subscribe to my weekly newsletter by filling in the form.

Get my latest content every week and 0 spam!