aws developer cloud

Scheduling AWS Lambdas, a 101

Creating an AWS Lambda and triggering on time

Shaun Wilde
an open diary with a pencil

I often find myself needing to schedule some automation and in the past I have (ab)used services such as Zapier or IFTTT (and other services of similar ilk) to achieve my goals. More recently I needed to do something for work, using the above services wouldn't cut it and I didn't have ready access to an internal cron-like service to do my bidding so I needed another approach.

Though not immediately obvious, well not initially to me at least, you can use an Eventbridge (or CloudWatch events) trigger with a cron expression and use that to kick off your lambda on a particular schedule.

To configure this in your template.yml it would look something like this

Resources:
  OperationToBeScheduled:
Type: AWS::Serverless::Function
Properties:
	  ...

  OperationToBeScheduledTrigger:
Type: AWS::Events::Rule
Properties:
  Description: trigger our scheduled lambda
  ScheduleExpression: cron(0 17 ? * SUN *)
  Targets:
    - Arn: !GetAtt OperationToBeScheduled.Arn

  OperationToBeScheduledLambdaPermission:
Type: AWS::Lambda::Permission
Properties:
  FunctionName: !GetAtt OperationToBeScheduled.Arn
  Action: lambda:InvokeFunction
  Principal: events.amazonaws.com
  SourceArn: !GetAtt OperationToBeScheduledTrigger.Arn

First, you need to create the trigger and configure the ScheduleExpression. Next, you need to grant the trigger the right to invoke your lambda when it fires.

The cron expression is in UTC only so you'll need to do the mental gymnastics to get the trigger to activate according to your timezone and if necessary take daylight savings into account as well.

The best part here is that I can have as many of these as I like and not have to take on any subscriptions with 3rd party services; though now I will probably need to keep more of an eye on my monthly AWS bill.

The above snippet is for my future self and I hope you find it useful. Your feedback, as always, is appreciated.