What is a Crontab?
You may have noticed in the past that AWS runs on Linux. Linux is part of a family of operating systems that are called Unix-like operating systems, and these operating systems have a built-in job scheduling utility called Cron. Cron jobs are driven by a crontab file, which is essentially a table filled with all the cron job rules.
There are a handful of ways to schedule jobs in AWS, but in the scope of this article, we’re just going to go over CloudWatch Events and Lambda.
Are Crontabs a good use-case for serverless applications?
Absolutely! One of the main goals of serverless is to automate anything and everything. Crontabs are an easy way to automate periodic jobs.
What does a CloudWatch Event look like?
The general architecture is very straightforward, but specific use-cases, and what your Lambda does can differ.
Basic file structure
The CloudWatch Event is considered a property of a specific Lambda function. In the Lambda’s
events object, add a new attribute of
Type: Schedule, then under that, a
The Schedule is a required attribute and takes one of two options:
rate(expression)- rate takes a simple recurring expression.
cron(cron expression)- cron takes a cron expression. Helpful if you have more complex scheduling needs.
Let’s build a new CloudWatch Event
Before we get started
You should already have a few things set up:
- AWS Credentials
- SAM CLI installed
Create a new project
Let’s make a new project:
It will ask you a few questions regarding the project setup. Once those are answered, hop into your new project, and change the app.js file to simply console log a message, so we know it’s working. It should look like this:
Add event triggers to the Lambda
As you can see, our Event (FunctionTrigger) is nested as a property of the Lambda itself. Within the event’s properties, we’ve given it a schedule that it will use to trigger the Lambda. In this case, it will run at 2 pm UST, or 6 am PST.
That’s all it takes to schedule a Lambda! After running sam deploy, you can verify that the Lambda is scheduled in the AWS console by going to CloudWatch > Events > Rules. You should see a rule there that, when clicked on, details the schedule and what it will trigger.
Scheduling is a simple yet powerful tool that allows you to automate many parts of serverless applications. Using a cron expression to schedule the job gives you very fine-grained control over when a job will run.