AWS CDK

Run AWS Lambda on schedule

Run AWS Lambda in a Cron-like fashion.

The AWS Lambda service is great for low powered foreground operations like responding to API calls, however, some people use Lambda also for doing medium powered semi-background operations such as periodically synchronizing data between two AWS services (e.g. two DynamoDB tables), aggregating data, sending emails, transitioning S3 files to different storage classes, creating scheduled reports, etc.

A common use case in these latter scenarios is to run the Lambda on a predictable schedule – also called Cron. AWS Lambda doesn’t have such built-in functionality. It can not self-invoke itself on schedule.

However, AWS CloudWatch Rules allows setting up such Cron rules.

import * as lambda from '@aws-cdk/aws-lambda';
import {Rule, Schedule} from '@aws-cdk/aws-events';
import {LambdaFunction} from '@aws-cdk/aws-events-targets';

const lambda = new lambda.Function(...);

new Rule(this, 'Rule', {
    description: "Schedule a Lambda that creates a report every 1st of the month",
    schedule: Schedule.cron({
        year: "*",
        month: "*",
        day: "1",
        hour: "1",
        minute: "1",
    }),
    targets: [new LambdaFunction(lambda)],
});

The above will run the Lambda on the first day of every month. You could adjust the cron expression as per your preferred schedule.

Need consulting? Get in touch

Comments

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.