Search code examples
amazon-web-servicesaws-cdk

How to run Lambda created in CDK on a regular basis?


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?


Solution

  • 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!