Quick Links

If you're looking to run code regularly, like a cron job, you can use AWS's CloudWatch Events to automatically run serverless Lambda Functions at fixed time intervals, without using any actual servers.

What Is CloudWatch Events?

CloudWatch is a service from AWS that monitors and responds to changes in your cloud infrastructure. It's most commonly used for logging and monitoring, but it more generally acts as the glue holding many applications together.

One of these features is CloudWatch Events, a service that basically maps cause to effect. There are a bunch of different actions that can trigger events, like spot instance interruption for EC2, bucket and object level operations for S3, etc. Then, it can trigger other actions, like running a lambda function, pub to SNS queue, or many other actions.

The trick, in this case, is that the event doesn't have to be triggered by something. There's another option for running events periodically, either by a fixed time interval like every five minutes, or by using cron syntax to define a specific period. You can bind this automatic event to Lambda function to have it run automatically.

Setting Up a Recurring Function

You'll, of course, need a function that you'll want to run. You can create these from the Lambda Management Console. If you just want a Hello World function to test with CloudWatch Events, you'll need to log the event to have a record of some output.

'use strict';

exports.handler = (event, context, callback) => {

console.log('LogScheduledEvent');

console.log('Received event:', JSON.stringify(event, null, 2));

callback(null, 'Finished');

};

Set up the function, and test it with the built in tools, and view the logs and recent invocations under the "Monitoring" tab.

lambda function

Head over to the CloudWatch Management Console to create a new rule, under Events > Rules in the sidebar.

create new rule

For the Event Source, switch it from "Event Pattern" to "Schedule" to set up automatic events. You can use the fixed rate, or use cron syntax to specify a more accurate time. You can read our guide to cron or use this online tool to help you with the syntax, but the general format is:

minute hour day month weekday

event source

For the target, add a new target and choose "Lambda Function." Select the name of the function you wish to run.

Add a new target, choose "Lambda Function."

Click "Configure Details," give it a name, and create the rule. Your Lambda function should begin executing, and you can view the logs for it from the Lambda's monitoring tab or from CloudWatch logs.