The common purposes of scheduling Lambda functions is to automate tasks such as nightly data backups, data fetching and processing, or any routine task that needs to run on a scheduled basis.
If you're using AWS as a cloud provider, once of the most common services to schedule your lambdas is EventBridge (formerly known as CloudWatch Events).
To show and example of how to create such thing, we'll use Terraform.
First, lets create the rule itself (eventually it'll be registered in EventBridge):
resource "aws_cloudwatch_event_rule" "schedule" {
name = "${var.name_prefix}-schedule"
description = "Schedule for Updater Lambda Function (ap-vpn-console)"
schedule_expression = var.schedule_expression
}
name: A unique identifier for the rule, using a variable for flexibility.
description: Clear description of what the rule does.
schedule_expression: When the Lambda will be triggered. Use the schedule_expression
variable to easily change the timing without modifying the code directly.
Just in case you're not familiar with cron expressions, here is an example:
variable "schedule_expression" {
description = "The schedule expression for the lambda function"
type = string
default = "cron(0 2,10 * * ? *)"
}
This cron expression means the Lambda will run at 2:00 AM and 10:00 AM (UTC) every day.
Now let's hook it with our Lambda function:
resource "aws_cloudwatch_event_target" "schedule_lambda" {
rule = aws_cloudwatch_event_rule.schedule.name
target_id = "processing_lambda"
arn = aws_lambda_function.lambda.arn
}
rule: Links the target to the previously defined rule.
target_id: An identifier for the target.
arn: Amazon Resource Name for the Lambda function to execute.
Last thing we might want to do, is to allow EventBridge to invoke the Lambda function by defining its permissions:
resource "aws_lambda_permission" "allow_events_bridge_to_run_lambda" {
statement_id = "AllowExecutionFromCloudWatch"
action = "lambda:InvokeFunction"
function_name = aws_lambda_function.lambda.function_name
principal = "events.amazonaws.com"
}
statement_id: A unique identifier for the statement.
action: Specifies the allowed action.
function_name: Links to the Lambda function.
principal: The AWS service that is allowed to perform the action.