Arpan Dutta
Arpan Dutta

Reputation: 75

Need to create a CloudWatch rule that runs only once at a specific date and time

I need to figure out the CRON expression to trigger a Lambda that runs 1 hour before a specified date and time. Example: I get a specific date and time from a SNS notification, say 20th May 2022, 4 pm UTC Now, I need to create a CRON expression for 20th May 2022, 3 pm UTC (i.e., 1 hour before the specific date and time), so that the Lambda is triggered an hour before the time.

I have gone through AWS docs and understand that I need to create a CRON expression to do this. I need help in figuring out the expression that would perform this and run only once.

Upvotes: 2

Views: 1602

Answers (1)

TheEdgeOfRage
TheEdgeOfRage

Reputation: 842

There are two variants to define schedule expressions. One is rate() that juts tells it how often to run, the other is cron(), which is a cron-like syntax. The full syntax for the cron call looks like this:

cron(Minutes Hours Day-of-month Month Day-of-week Year)

So in your example you can use:

cron(0 15 20 5 ? 2022)

Note that all fields accept * as the wildcard, except the Day-of-week one, which uses ?.

To actually generate this from an SNS event, you can create another Lambda function that listens to SNS events, reads the desired timestamp, and creates a new EventBridge rule with the timestamp converted to the cron format as the ScheduleExpression. Depending on the language that you use in the Lambda, use the appropriate AWS SDK to create the EventBridge rule and target. For example, if you use Python, you can use the boto3 put_rule method and then call put_target to attach the new rule to the other Lambda function that runs the scheduled code.

Also, I believe that scheduled events are only available on the default EventBridge, not on custom ones. I know this used to be a limitation before, they might have changed it in the meantime.

Upvotes: 3

Related Questions