How To Trigger A Lambda On A Timer Via AWS Console & Serverless Framework
Tags: aws, lambda, beginners, tutorial
Published: 2023-02-11 05:00:00



In this post, we will learn how to trigger a Lambda function on a timer. We will learn two different methods of achieving this. The first method is using the AWS console and the second method is using the Serverless framework.

If you prefer to watch a video I have this tutorial recorded and available below:

{% embed https://youtu.be/nn14q7ubE5c %}

## Method 1: Triggering a Lambda Function using the AWS Console

The first thing we are going to do is go to our AWS Lambda section in the AWS Console and create a simple Lambda function that logs a scheduled event. The function’s name is `LogScheduledEvent `and the following is the code for the handler:

```
'use strict';

export const handler = (event, context, callback) => {
  console.log('LogScheduledEvent');
  console.log('Received event:', JSON.stringify(event, null, 2));
  callback(null, 'Finished');
};
```

After creating the function and replacing the index.mjs with the above code. Look at the function overview and click on the “Add trigger” button.

![Add Trigger Button in Function Overview](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5gu81fsbfdh2au95oftk.png)

In the “Select a source” section search for `EventBridge`. You may see `EventBridge (CloudWatch Events)`, EventBridge used to be called CloudWatch Events that’s why there are the parentheses CloudWatch Events but probably over time those parentheses are going to go away so just look for it at EventBridge.

We’re going to create a new rule, so chose the “Create a new rule” radio box and name it `5Minutes`. This trigger is a scheduled expression, we just want it to run every five minutes.

That’s the difference between the expression choices we have (Scheduled Expression and Event Pattern). An event pattern is triggered by a specific event. So, for example, you could have an auto-scaling event that occurs when an instance is launched or auto-scaling terminates one of your EC2 instances. In this case, you may want to trigger your Lambda function. The are a lot more options you can also do and I suggest looking at the options, but right now we’re keeping this simple we’re just doing a scheduled expression. With a scheduled expression you can use either cron or rate expressions.

We are going to use a rate expression so we will put `rate(5 minutes)` in the schedule expression. You can learn more about Cron or rate expressions [here](https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/ScheduledEvents.html).

![Add Trigger Set Up](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k7uij19nzyy7hfu3tmmd.png)

After populating all the fields click “Add.”

Congrats you just created a Lambda function on a timer using the AWS console. Make sure you verify that the trigger has been added successfully by checking the monitoring section in AWS Lambda and the EventBridge events. You can also view the logs in AWS CloudWatch to see the events that are being received.

## Method 2: Triggering a Lambda Function using the Serverless Framework

This method assumes you have already set up Serverless framework on your machine and have connected it to your AWS account. If you need help doing this I do have a video [here](https://youtu.be/xPzDS2TkEXQ).

First create a new Serverless project and add the following code to your handler:

```
'use strict';

module.exports.LogScheduledEventServerless = (event, context, callback) => {
  console.log('LogScheduledEvent');
  console.log('Received event:', JSON.stringify(event, null, 2));
  callback(null, 'Finished');
};
```

In the serverless.yml file, we can define the schedule for the function as the following:

```
service: aws-log-schedule-event

frameworkVersion: '3'

provider:
  name: aws
  runtime: nodejs18.x

functions:
  LogScheduledEventServerless:
    handler: handler.LogScheduledEventServerless
    events:
      # Invoke Lambda function every 5 minutes
      - schedule: rate(5 minutes)
```

To break down the above YAML file. How you schedule the events in serverless is pretty simple. Serverless actually has a property called events and within events, you determine the schedule. So in this case we are invoking the function every five minutes. In serverless YAML you can actually attach multiple schedules to your Lambda so if we wanted to we could also schedule using that cron expression.

`- schedule: cron(*/5 * ? * MON-FRI *)`

This would run the function every five minutes on Monday through Friday. To have multiple schedules you would change your events property to look something like this:

```
    events:
      # Invoke Lambda function every 5 minutes
      - schedule: rate(5 minutes)
      # Invoke Lambda function every 5 minutes from Mon-Fri
      - schedule: cron(*/5 * ? * MON-FRI *)
```

Something to keep in mind is that events are enabled by default. If you wanted it to not be enabled you need to add that like so:

```
    events:
      # Invoke Lambda function every 5 minutes
      - schedule: rate(5 minutes)
          enable: false
```

After adding the event to your `serverless.yml` you can deploy the code using the command serverless deploy

Make sure you verify that the function has been deployed successfully and that the EventBridge trigger has been added. Don’t forget that you can view the recent invocations and the logs in AWS CloudWatch to see the events that are being received.

Congratulations you have just learned how to trigger a Lambda function on a timer using both the AWS console and the Serverless framework. These methods are easy to implement and will allow you to schedule your Lambda functions to run at specific intervals. Happy learning!