Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 677
Jamie Avatar asked Nov 25 '19 17:11

Jamie


People also ask

Can Lambda run continuously?

Historically, the maximum execution timeout limit was 5 minutes. At the time of writing this article, AWS Lambda functions cannot run continuously for more than 15 minutes. This is a hard limit in the AWS Lambda service. In practice, there are use cases for which those 15 minutes are not enough.


1 Answers

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!

like image 170
Jamie Avatar answered Oct 21 '22 01:10

Jamie