8

As the title says - I've created a Lambda in the Python CDK and I'd like to know how to trigger it on a regular basis (e.g. once per day).

I'm sure it's possible, but I'm new to the CDK and I'm struggling to find my way around the documentation. From what I can tell it will use some sort of event trigger - but I'm not sure how to use it.

Can anyone help?

Jamie
  • 1,530
  • 1
  • 19
  • 35

2 Answers2

30

Sure - it's fairly simple once you get the hang of it.

First, make sure you're importing the right libraries:

from aws_cdk import core, aws_events, aws_events_targets

Then you'll need to make an instance of the schedule class and use the core.Duration (docs for that here) to set the length. Let's say 1 day for example:

lambda_schedule = aws_events.Schedule.rate(core.Duration.days(1))

Then you want to create the event target - this is the actual reference to the Lambda you created in your CDK earlier:

event_lambda_target = aws_events_targets.LambdaFunction(handler=lambda_defined_in_cdk_here)

Lastly you bind it all together in an aws_events.Rule like so:

lambda_cw_event = aws_events.Rule(
    self,
    "Rule_ID_Here",
    description=
    "The once per day CloudWatch event trigger for the Lambda",
    enabled=True,
    schedule=lambda_schedule,
    targets=[event_lambda_target])

Hope that helps!

Jamie
  • 1,530
  • 1
  • 19
  • 35
  • This is exactly what I did. Thanks! – Jamie Nov 25 '19 at 17:51
  • 1
    Great answer! It's even easier now with CDK 2.0: https://docs.aws.amazon.com/cdk/api/latest/python/aws_cdk.aws_events/Schedule.html – awerchniak Dec 08 '21 at 20:12
  • Thanks for the comment @AndyW although the link you sent is still CDK v1. You'll want /api/v2 instead of /api/latest for CDK v2 – Jamie Dec 09 '21 at 21:04
2

The question is for Python but thought it might be useful to post a Javascript equivalent:

const aws_events = require("aws-cdk-lib/aws-events");
const aws_events_targets = require("aws-cdk-lib/aws-events-targets");

const MyLambdaFunction = <...SDK code for Lambda function here...>

new aws_events.Rule(this, "my-rule-identifier", {
    schedule: aws_events.Schedule.rate(aws_cdk_lib.Duration.days(1)),
    targets: [new aws_events_targets.LambdaFunction(MyLambdaFunction)],
});

Note: The above is for version 2 of the SDK - might need a few tweaks for v3.

Steve Chambers
  • 37,270
  • 24
  • 156
  • 208