Suppose you have written a Lambda function and you want it to run every x hours or minutes, how can you achieve such a thing?
The answer is using AWS CloudWatch Rules. You can setup a Lambda function or any other supported AWS services for that matter to trigger on a rate that you specify.

How to deploy the trigger with Lambda Deployment
Now we can manually set the Rules in AWS CloudWatch after our Lambda function has been deployed. But what if you want the schedule to be a part of the AWS SAM template so that when you deploy your Lambda function, the schedule is also automatically deployed as a part of the AWS CloudFormation stack?
This post answers the above question. Open your AWS SAM template, template.yaml
(more info on AWS SAM template here). The section for your Lambda function will look similar to this:
HeavydutyLambdaFunction:
Type: 'AWS::Serverless::Function'
Properties:
Handler: HeavydutyLambdaFunction/index.handler
Runtime: nodejs8.10
Description: ''
MemorySize: 512
Timeout: 60
Role: 'arn:aws:iam::068795894039:role/HeavyDuty-Role'
Events:
LambdaMicroservice:
Type: Api
Properties:
Path: /heavyduty
Method: GET
Now add the following element at the very end, under Events
:
HeavyDutyScheduledEvent:
Type: Schedule
Properties:
Schedule: rate(1 hour)
So that now your Lambda function definition becomes:
HeavydutyLambdaFunction:
Type: 'AWS::Serverless::Function'
Properties:
Handler: HeavydutyLambdaFunction/index.handler
Runtime: nodejs8.10
Description: ''
MemorySize: 512
Timeout: 60
Role: 'arn:aws:iam::068795894039:role/HeavyDuty-Role'
Events:
LambdaMicroservice:
Type: Api
Properties:
Path: /heavyduty
Method: GET
HeavyDutyScheduledEvent:
Type: Schedule
Properties:
Schedule: rate(1 hour)
Next, deploy your serverless application using the AWS SAM template. To verify that your CloudWatch Rules have been deployed:
- Open the CloudWatch console.
- On the left sidebar, under
Events
, clickRules
. - Click your recently deployed Lambda function.
- You will see something like this:

A few things to keep in mind:
- You can define the name of your event here and it can be anything. Here it is
HeavyDutyScheduledEvent
. - The unit for the
Schedule
can be minute(s), hour(s) or day(s). - If the minutes, hours or days are more than 1, then you need to specify the unit in plural form. Some examples:
- rate(10 minutes)
- rate(1 minute)
- rate(8 hours)
- rate(1 hour)
- rate(3 days)
- rate(1 day)
- You can specify
rate expressions
for fixed intervals, or you can specifyCron Expressions
for more fine grained control, where you can specify that the job will run on which minute, hour & day for which week or month.
You can find more information on this Rules Expressions on AWS Official docs.