How to Use AWS Lambda Functions as Cron Jobs: Complete Guide
By Braincuber Team
Published on April 10, 2026
What You'll Learn:
- What Amazon CloudWatch Events are and how they trigger Lambda functions
- How to define Lambda functions as infrastructure using AWS SAM
- How to write and deploy Lambda code for starting and stopping EC2 instances
- How to set up cron expressions for scheduling Lambda functions
- How to clean up resources after completing the tutorial
Cron jobs are utilities used by system administrators to schedule commands at specific times. They handle tasks like running backups, monitoring system status, and performing system maintenance. When administering systems in the cloud, cron jobs remain essential for automating administrative tasks.
One modern approach to running cron jobs in the cloud is using Function as a Service (FaaS), like AWS Lambda. Lambda functions execute when triggered and run code in the cloud without provisioning or maintaining infrastructure. Functions can be configured to run at specific times or with certain periodicity, just like traditional cron jobs.
Understanding Amazon CloudWatch Events
In order to use a Lambda function as a cron job, you need to understand Amazon CloudWatch Events. CloudWatch Events are sent automatically when there are changes in your AWS resources, and these events can trigger Lambda functions.
When your AWS resources change state, they send CloudWatch Events to an event stream. You can create rules that trigger specific Lambda functions when certain events occur. For example, you can automatically invoke a Lambda function when there is a change in an AutoScaling group.
CloudWatch Events can also invoke Lambda functions on a regular schedule. This allows you to create Lambda functions that turn off development EC2 instances after 6pm and turn them back on after 8am, saving costs on resources that only need to run during business hours.
How CloudWatch Events Work with Lambda
- AWS Resource Changes State - An EC2 instance, AutoScaling group, or other resource changes
- CloudWatch Event Generated - An event is automatically sent to the CloudWatch event stream
- Rule Matches Event - A CloudWatch rule you created matches the event pattern
- Lambda Triggered - The associated Lambda function is invoked
- Function Executes - Your Lambda code performs the desired action
Setting Up the Demo Environment
This tutorial demonstrates a Lambda function that performs actions on EC2 instances. We will use AWS SAM (Serverless Application Model) to define our Lambda function as infrastructure as code.
Prerequisites:
- An AWS account with one or more EC2 instances
- AWS SAM CLI installed (or use AWS Cloud9 IDE where SAM is pre-configured)
- Basic understanding of Node.js or Python
What We Will Build:
- A Lambda function that starts EC2 instances at 8am daily
- A Lambda function that stops EC2 instances at 6pm daily
- CloudWatch Event rules to trigger these functions on schedule
The complete code for this example is available in this GitHub repository. To get started with AWS Cloud9 IDE, configure your GitHub account and clone the repository inside the IDE.
Deploying with AWS SAM
AWS SAM (Serverless Application Model) allows you to define your serverless applications using a simplified YAML syntax. Once defined, SAM CLI deploys your application to AWS CloudFormation.
After cloning the repository, deploy the project using:
sam deploy --guided
The guided deployment will ask you to answer several questions:
| Configuration | Description |
|---|---|
| Project Name | A unique name for your SAM project |
| AWS Region | Select the same region where your EC2 instances are located |
| Instance IDs | Comma-separated list of EC2 instance IDs to control |
Defining the Lambda Function with AWS SAM
The Lambda function is defined in the template.yml file using AWS SAM syntax. Here is a breakdown of the key components:
Function Name (StartInstanceFunction)
The logical identifier for your Lambda function within the template.
Handler
Specifies the module and method that executes when the function is invoked. Format: filename.methodName.
CodeUri
The path to the directory containing your function code. In this case, cron/handler.js.
Runtime
The execution environment. This tutorial uses Node.js 12, but Lambda supports Python, Java, Go, C#, and custom runtimes.
Environment Variables
Dynamic values passed to your function at runtime. We use this to specify which EC2 instances to control.
Policies (IAM Permissions)
Lambda functions execute without permissions by default. You must explicitly grant access to AWS resources. The policy below allows starting all EC2 instances.
Events (CloudWatch Schedule)
Defines how the Lambda is triggered. We use a cron expression to schedule execution at 8am daily.
Understanding CloudWatch Cron Expressions
CloudWatch Events use cron expressions with the format: cron(Minutes Hours Day-of-month Month Day-of-week Year)
| Expression | Description |
|---|---|
cron(0 8 * * ? *) | Every day at 8:00 AM UTC |
cron(0 18 * * ? *) | Every day at 6:00 PM UTC |
cron(0 8 ? * MON-FRI *) | Weekdays at 8:00 AM UTC |
cron(0 */4 * * ? *) | Every 4 hours |
Important: Use UTC Timezone
CloudWatch cron expressions are evaluated in UTC. Adjust your times accordingly based on your local timezone.
Writing the Lambda Function Code
The Lambda handler code is located in cron/handler.js. This function starts the specified EC2 instances when triggered by the CloudWatch Event.
const AWS = require('aws-sdk');
const ec2 = new AWS.EC2();
exports.startInstance = async (event) => {
const instanceIds = process.env.INSTANCE_IDS.split(',');
try {
const result = await ec2.startInstances({ InstanceIds: instanceIds }).promise();
console.log('Started instances:', instanceIds);
return { statusCode: 200, body: JSON.stringify(result) };
} catch (error) {
console.error('Error starting instances:', error);
return { statusCode: 500, body: JSON.stringify({ error: error.message }) };
}
};
exports.stopInstance = async (event) => {
const instanceIds = process.env.INSTANCE_IDS.split(',');
try {
const result = await ec2.stopInstances({ InstanceIds: instanceIds }).promise();
console.log('Stopped instances:', instanceIds);
return { statusCode: 200, body: JSON.stringify(result) };
} catch (error) {
console.error('Error stopping instances:', error);
return { statusCode: 500, body: JSON.stringify({ error: error.message }) };
}
};
How the Code Works
Environment Variable
The INSTANCE_IDS environment variable contains comma-separated EC2 instance IDs. This allows changing target instances without modifying code.
AWS SDK
The AWS SDK for JavaScript provides methods like startInstances and stopInstances to control EC2 resources programmatically.
Async/Await Pattern
Using async/await makes the code cleaner and easier to read. The SDK methods return Promises that resolve when the action completes.
Error Handling
Try/catch blocks ensure that any errors during EC2 operations are logged and returned with an appropriate HTTP status code.
Running the Scheduled Cron Job
After deploying the two Lambda functions to your AWS account in the same region as your EC2 instances, they will execute automatically at the scheduled times.
To test immediately:
- Modify the cron expression in the CloudWatch Event to trigger at a time you can observe
- Ensure your EC2 instance state matches what you expect (on if testing stop, off if testing start)
- Wait for the scheduled time or manually trigger the Lambda from the AWS Console
After deployment, go to the EC2 Console to see your instances automatically start at 8am and stop at 6pm. This automation continues indefinitely until you remove the Lambda functions.
Cost Optimization Tip
This pattern is excellent for saving costs on development and testing environments. Stop instances outside business hours to reduce EC2 running time by up to 65%.
Cleaning Up Resources
After completing this tutorial, clean up the resources to avoid ongoing charges:
Remove Lambda Functions
Go to AWS CloudFormation in the Management Console and delete the stack created by SAM. This removes all Lambda functions, IAM roles, and CloudWatch Event rules.
Terminate EC2 Instances
If you created EC2 instances specifically for testing, terminate them from the EC2 Console to stop all associated charges.
Delete CloudWatch Logs
Lambda functions create CloudWatch Logs that accumulate over time. Consider setting up log retention policies or deleting log groups manually.
# Delete the entire CloudFormation stack
aws cloudformation delete-stack --stack-name lambda-cronjobs
# Or from the AWS Console:
# 1. Open CloudFormation
# 2. Select your stack
# 3. Click Delete
Conclusion
AWS Lambda functions combined with CloudWatch Events provide a powerful serverless solution for automating tasks in your AWS infrastructure. Key benefits include:
Cost Effective
Lambda pricing is based on execution time (in 100ms increments). For infrequent tasks, this is far cheaper than running a dedicated server 24/7.
No Infrastructure
No servers to provision, maintain, or scale. AWS handles all the underlying infrastructure automatically.
Event-Driven
Lambda can respond to hundreds of AWS event types, not just schedules. React to S3 uploads, DynamoDB changes, API calls, and more.
Flexible Runtimes
Choose from Node.js, Python, Java, Go, Ruby, or bring your own custom runtime for complete flexibility.
With CloudWatch Events, you can receive notifications about any changes in your AWS resources and access almost all AWS services using the SDK. This enables automating maintenance tasks and infrastructure management at scale.
Frequently Asked Questions
How much does Lambda cost for cron jobs?
Lambda charges $0.20 per 1 million requests and $0.0000166667 per GB-second of execution time. For daily cron jobs running a few seconds, costs are typically less than $1 per month.
What is the maximum Lambda execution time for cron jobs?
The default maximum execution time is 15 minutes. For most cron job tasks like starting/stopping instances, execution completes in seconds.
Can Lambda cron jobs run on weekends only?
Yes, use the day-of-week field in cron expressions. For example, cron(0 8 ? * MON-FRI *) runs only Monday through Friday at 8 AM.
What happens if a Lambda cron job fails?
Failed executions are logged to CloudWatch Logs. You can set up CloudWatch Alarms to notify you via SNS when a Lambda function fails, enabling quick response.
How do I secure Lambda functions that control EC2 instances?
Grant only the specific permissions needed using IAM policies. Instead of "Resource": "*", specify exact instance ARNs: "Resource": "arn:aws:ec2:region:account:instance/instance-id".
Need Help with AWS Lambda?
Our AWS experts can help you design and implement serverless automation solutions for your infrastructure.
