Applicable when
- Lambda needs to be created which is run as per a schedule. For example, run lambda once every 5 min
Implementation
First, you need to create a lambda function as normal in CDK,
import { Function as LambdaFunction } from "@aws-cdk/aws-lambda";
const lambdaName = "polling-lambda";
const pollingLambda = new LambdaFunction(this, lambdaName, {
handler: "lambda-polling/handler.handler",
functionName: lambdaName,
// ... other lambda props go here
});
Then you need to create a lambda event target,
import { LambdaFunction as EventTargetFunction } from '@aws-cdk/aws-events-targets';
const pollingLambdaTarget = new EventTargetFunction(pollingLambda);
Note that the LambdaFunction is imported from '@aws-cdk/aws-events-targets' and not '@aws-cdk/aws-lambda'. This function takes in an AWS Lambda Function and returns a RuleTarget.
We can then create our rule with our rule target,
import { Rule, Schedule } from '@aws-cdk/aws-events';
import { Duration } from '@aws-cdk/core';
new Rule(this, 'lambda-polling-rule'), {
description: 'Rule to trigger scheduled lambda polling',
// schedule specifies once every 5 minutes, target must be run
schedule: Schedule.rate(Duration.minutes(5)),
targets: [pollingLambdaTarget],
});
Once your changes are deployed, you can see the rule with details about your target and rate in the `Amazon EventBridge` service of your AWS console.
Note that you can have other types of scheduling rules such as schedule expression and cron fields. You can also have several targets such as API Gateway, SNS topic, Kinesis stream, etc.
Comments
0 comments
Please sign in to leave a comment.