Serverless Framework CRON JOB Scheduler Offline Local Testing Node JS

In this article, We will discuss how we can test Serverless Framework CRON Job Scheduler Offline or Local using a Node JS.

Sometimes you need to test functionality locally on your system for instance you have Serverless Function (AWS lambda) that schedule to execute every 30 minutes to perform any X or Y task. So the question is how do you test it locally before deploying to the AWS environment?

We will teach you don’t worry :) there are many benefits of testing locally before deploying to the AWS environment such as

  1. Save Cost
  2. Save Time
  3. Test Performance Locally

Video

Let’s Start

What is CRON JOB Scheduler?

A task that executes in the background on a particular or defined date/time called CRON JOB

Example:

You have the task or function to check the user's birthday every 24 hrs from the database and trigger the email if the user has a birthday.

//#### Just for your refernce
function checkBirthday() {
if(user.hasBirthday) {

sendEmail(user.Email);
}}

Make sure you have installed Node JS on your system we are using Node v12.0

We recommend you install NVM (Node Version Manager) wrote the following article.

Install the Serverless Framework

Install via npm:

npm install -g serverless

You will see the following screen if installed successfully

Create a new service

serverless create --template aws-nodejs --path local-scheduler

Now change directory to local-scheduler

cd local-scheduler

If you open the local-scheduler directory in any editor you will see these files handler.js and serverless.yml shown below

We used a Visual Studio Code in the following screenshot.

  1. handler.js

2. serverless.yml

if you run the function locally using the following command

sls invoke local -f hello -l

It will print the following output

Now we want to configure the hello should trigger in every 1 minute to do that we need to install a serverless-offline-scheduler plugin using the following command

npm install serverless-offline-scheduler

When you are done with the plugin installation you will see the following screen

Now we need to add this plugin to our serverless.yml file as following

After adding the plugin we need to schedule the function. We are scheduling the hello function to execute every 1 minute to do that we need to add an event to the function in the serverless.yml file as shown below.

Run Scheduler

To run scheduler type the following command

sls schdule

After, you will see scheduler is running as shown below

After 1 minute it will execute the hello function as shown below

Github

Thank you 🚀🚀🚀🚀🚀🚀🚀🚀

Written by

We teach & develop for startups

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store