Skip to main content

Create scheduled tasks using cron expressions or one-time events

· 3 min read
Javid
Creator & Software Engineer

Create scheduled tasks using cron expressions or one-time events

Introduction

EventBridge Scheduler allows you to schedule one-time or recurring events. It can invoke many targets like AWS Lambda, SQS, SNS, etc. In this blog, we will focus on AWS Lambda as a target.

tip

The serverless kit includes the complete code and resources for creating a scheduler. When you purchase the kit and deploy your app, it will automatically create all the resources for you.

Overview

The upstream service will create a scheduler using the AWS SDK v3. It can be a Lambda function, ECS, EC2 etc. The AWS Event Scheduler will invoke the Lambda function at the scheduled time.

graph LR
A[Upstream Service] --> B[AWS EventBridge Scheduler]
B --> C[AWS Lambda Function]

How to create a scheduler

There are several ways to create a scheduler. For example ClickOps (Using AWS management console), CLI, or SDK. We will use AWS SDK v3 and Node.js to create a scheduler.

Here is the code snippet to create a one-time scheduler using the AWS SDK v3.

// create-scheduler.tsx

import {
ActionAfterCompletion,
CreateScheduleCommand,
CreateScheduleCommandInput,
FlexibleTimeWindowMode,
} from '@aws-sdk/client-scheduler';

const payload = {
key: 'value',
sender: 'upstream-service',
};
const date = '2024-02-24';
const time = '12:00';

const scheduleExpression = `at(${date}T${time}:00)`;

const schedulerCommandInput = {
Name: 'scheduler-name',
/**
* You can create a custom group to group the relevant schedulers.
* If you don't create it, it will use the default group.
*/
GroupName: 'default',
ActionAfterCompletion: ActionAfterCompletion.DELETE,
ScheduleExpression: scheduleExpression,
FlexibleTimeWindow: {
Mode: FlexibleTimeWindowMode.OFF,
},
Target: {
Input: JSON.stringify(payload),
Arn: '<scheduledEventLambdaArn>',
RoleArn: '<scheduledEventRoleArn>',
RetryPolicy: {
MaximumEventAgeInSeconds: 60,
MaximumRetryAttempts: 3,
},
},
};

const createSchedulerCommand = new CreateScheduleCommand(schedulerCommandInput);
await schedulerClient.send(createSchedulerCommand);

Let's break down the code snippet:

  • payload: The payload that the target service (Lambda function) will receive when the scheduler invokes it.
  • scheduleExpression The syntax to schedule one-time events. Check the AWS documentation for more details.
  • schedulerCommandInput: The input for the CreateScheduleCommand command.
  • createSchedulerCommand: The command to create a scheduler.
  • Target Arn: The ARN of the target service (Lambda function).
  • RoleArn: The ARN of the role that will be used by the EventBridge Scheduler to trigger the Lambda function.

How to create the role for the scheduler

You can create a role using the AWS management console, CLI, or IaC (Infrastructure as Code). I'm a big fan of managing the infrastructure using IaC. Here is the code AWS CDK code snippet to create the role.

import { aws_iam } from 'aws-cdk-lib';

const role = new aws_iam.Role(this, 'Role', {
assumedBy: new aws_iam.ServicePrincipal('scheduler.amazonaws.com'),
});

role.addToPolicy(
new aws_iam.PolicyStatement({
sid: 'ScheduledEventLambdaInvokePolicy',
actions: ['lambda:InvokeFunction', 'iam:PassRole'],
resources: [lambda.functionArn], // The ARN of the Lambda function
})
);

How to treat the scheduler

The downstream service will receive the payload at the specified time. This is the code snippet for a Lambda function that will receive the payload.

// index.ts

export async function handler(
event: unknown // the payload
): Promise<void> {
const { key, sender } = event;
// handle the payload
}

Note that you don't need to deserialize the payload.