About Amazon EventBridge Scheduler
Tags: aws, serverless, beginners, productivity
Published: 2023-01-04 20:34:36

Have you worked with Amazon EventBridge Rules? Have you tried creating cron jobs? or even made scheduled tasks? well for sure you have, Amazon released a new feature called Amazon EventBridge Scheduler, which makes our work more efficient and smoother.

### About EventBridge Scheduler:

Amazon EventBridge Scheduler is a serverless scheduler that allows you to create, run, and manage tasks from one central, managed service. Highly scalable, EventBridge Scheduler allows you to schedule millions of tasks that can invoke more than 270 AWS services and over 6,000 API operations.

EventBridge Scheduler delivers your tasks reliably, with built-in mechanisms that adjust your schedules based on the availability of downstream targets. With it, you can create schedules using cron and rate expressions for recurring patterns, or configure one-time invocations. You can set up flexible time windows for delivery, define retry limits, and set the maximum retention time for failed triggers.

### Examples:
Before using aws-sdk we need to give the required permissions to our scheduler, an IAM role that EventBridge Scheduler assumes in order to interact with other AWS services. (we named it `Scheduler_Role` the name will be used later inside the sdk)
```json
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "Service": "scheduler.amazonaws.com"
            },
            "Action": "sts:AssumeRole"
        }
    ]
}
```
The following policy will be shown under Trust relationships section, now in order my Scheduler is able to trigger Lambda function let us attach the following policy that I created.
```json
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "lambda:*"
            ],
            "Effect": "Allow",
            "Resource": "*"
        }
    ]
}
```

The architure that we will buid:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hel8ihfqpjubj5tmzzx5.png)

◻️ `aws-sdk` functions that will be used in this example:
- `createSchedule(params = {}, callback) ⇒ AWS.Request`
- `deleteSchedule(params = {}, callback) ⇒ AWS.Request`

> 📋 **Note:** You can visit the official sdk page via this [link](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Scheduler.html)

When the user does an API call, will create our EventBridge Scheduler:
```javascript
const result = await this.schedulerService.createSchedule();
```
```javascript
createSchedule() {
  const input = {
    id: '1234',
    name: 'hello world',
  };

  const payload = {
    FlexibleTimeWindow: {
      Mode: 'OFF',
    },
    Name: 'test_scheduler',
    ScheduleExpression: 'at(2022-12-26T14:46:00)',
    Target: {
      Arn: `arn:aws:lambda:${process.env.AWS_REGION}:${process.env.AWS_ACCOUNT_ID}:function:myTestLambda`,
      RoleArn: `arn:aws:iam::${process.env.AWS_ACCOUNT_ID}:role/Scheduler_Role`,
      DeadLetterConfig: {
          Arn: `arn:aws:sqs:${process.env.AWS_REGION}:${process.env.AWS_ACCOUNT_ID}:test-queue`,
      },
      Input: JSON.stringify(input),
      RetryPolicy: {
        MaximumEventAgeInSeconds: 300,
        MaximumRetryAttempts: 1,
      },
    },
    ScheduleExpressionTimezone: 'EET',
  };
  return this.scheduler.createSchedule(payload).promise();
}
```
Let us have a quick overview of the parameters that we are passing
- Name: the name of schedule
- ScheduleExpression: `at` - `at(yyyy-mm-ddThh:mm:ss)` / `rate` - `rate(unit value)` / `cron` - `cron(fields)`
- Target: My Lambda Arn since I am using as target
- RoleArn: the one that we created earlier `Scheduler_Role`
- DeadLetterConfig: Amazon SQS queue arn that EventBridge Scheduler uses as a dead-letter queue for your schedule. If specified, EventBridge Scheduler delivers failed events that could not be successfully delivered to the target
- Input: to keep it simple I added some hard coded object in the function, but most of the time this should be taken from Body, or database query based on your needs, and make sure its JSON.stringify()
- RetryPolicy: the time that you want retry happen and the number of attempts
- ScheduleExpressionTimezone: The time zone that you want the scheduler be triggered

Now once the scheduled date is reached, the Scheduler will trigger our Lambda function, in which we will remove our EventBridge Scheduler
```javascript
const result = await this.schedulerService.deleteSchedule();
```
```javascript
deleteSchedule() {
  const payload = {
    Name: 'test_scheduler',
  };
  return this.scheduler.deleteSchedule(payload).promise();
}
```
You can pass the name of the Scheduler from the Input in case you are using dynamically generated names 🙂

## Conclusion
In This article we saw how the new Amazon EventBridge Scheduler works, by keeping it simple and straight forward, I wanted to give a real life example where you want to schedule a simple Lambda function, and then maybe you want to remove that schedule.

This article is part of "Messaging with Serverless" series that I've been writing for a while, if you are interested to read about other Serverless offerings from AWS, feel free to visit the links below.