Automation in Node.js: Schedule Cron Jobs with node-cron

Node.js automation is essential in making routine tasks such as sending daily reports, database cleanup, or reminders more manageable. Thanks to cron jobs, developers find it easy to schedule tasks for certain times or intervals. If you ever needed to schedule Cron Jobs in Node.js for sending birthday emails or automatically updating logs, this tutorial will guide you step by step on how to do so using the node-cron package.

Using Node.js automation via cron, you are able to automate processes which repeat regularly without having to do them manually. Whether it’s updating user information every hour or performing a system backup on a daily basis, cron configuration in Node.js makes it hassle-free and effective.

What is a Cron Job and Why Use It

A cron job is an automatic task that occurs at a particular time, date, or frequency. It’s commonly used in server-side development to do repetitive work such as sending reports, generating notifications, or deleting files. Simply put, it facilitates automatization so developers don’t have to worry about running scripts manually each time.

What is node-cron?

Whereas the traditional cron jobs are set up at the operating system level, node-cron brings this mighty scheduling feature right into your application’s environment. It is a lightweight, easy-to-use Node.js module that enables you to schedule jobs using the well-known cron format.

The largest benefit is that your automation logic resides with the rest of your project code. This has your project as self-contained, easier to maintain, and simpler to deploy. You no longer must SSH into a server to update a system file; your scheduled jobs are part of your application.

Understanding Cron Job Timing

Before moving forware, you need to understand how timing works with cron job. A cron expression contains execution timing which defines when a scheduled task will run. Each expression has five positions representing minutes, hours, days, months, and weekdays. You can customize it to fit your specific needs.

Here are a few examples:

  • * * * * Run every minute
  • 0 * * * * Run every hour at the beginning of the hour
  • */5 * * * * Run every 5 minutes
  • 0 0 * * * Run every day at midnight

Setting up Node.js Application

Let’s start by creating a new Node.js project. You can use existing application to bur for clear approach we have used new application. Skip this step for existing node.js app. Open your terminal and run:

mkdir node-cron-automation
cd node-cron-automation
npm init -y

touch server.js

Here it will create new Node.js project. It will also create server.js file where you will add you code for cron jobs.

Installing node-cron Package

To add scheduling capabilities, we need to install the node-cron package. We will also install express to simulate a real-world server environment where these tasks would run.

Run this command in your terminal:

npm install express node-cron

Examples of Cron Setup in Node.js

Now for the exciting part! Let’s write the code to schedule two different tasks: a daily task and a task that runs every minute. Add the following code to your server.js file.

const express = require('express');
const cron = require('node-cron');

const app = express();
const PORT = 3001;

app.get('/', (req, res) => {
    res.send('Automation server is running! Scheduled jobs are active in the background.');
});

function sendBirthdayWishes() {
    console.log('Good Morning! Checking the database for users with birthdays today...');
    console.log('Sending birthday wishes!');
}

function monitorSystemHealth() {
    console.log('Checking system health... All services are running smoothly.');
}

app.listen(PORT, () => {
    console.log(`Server is running on http://localhost:${PORT}`);

    cron.schedule('0 9 * * *', () => {
        sendBirthdayWishes();
    }, {
        timezone: "America/New_York"
    });

    cron.schedule('* * * * *', () => {
        monitorSystemHealth();
    });
});

In this example, we have two scheduled tasks. The first one is for Birthday Wish, where the command runs the sendBirthdayWishes function every morning at 9:00 AM. This setup is ideal for tasks that need to occur once a day, such as sending personalized birthday messages or daily reports.

The second job is an Health Check, which uses every minute cron timing to run the monitorSystemHealth function. It’s idle for real-time data polling from an API. Here, it does not perform any actual logic for sending wises or checking system. It’s just conceptual example you can customize it as per your requirements and needs.

Running the Server and Testing

It’s time to see your automation in action. Start your server from the terminal:

node server.js

Once, server is started you will see messages for checking system and exactly at 9 AM you will see message for birthday wishes.

Conclusion

Through the installation of cron job in Node.js with node-cron, repetitive tasks become automated without any hassle. Whether it is the sending of notifications, the creation of daily reports, or data consistency maintenance, Node.js automation through cron ensures your operations run harmoniously without interruption from humans. Through cron jobs in Node.js, not only is time saved but the reliability and performance of your app are boosted as well.

If you’re exploring ways to enhance your Node.js projects, don’t miss our detailed guide on Top 20 Node.js Packages. It covers some of the most powerful and time-saving libraries that can help you.