DEV Community

Frank Joseph
Frank Joseph

Posted on

How to build a Cron Job using Node.js

Introduction
A cron job is a time-based task scheduler commonly used to automate repetitive tasks on a Linux or Unix-based system. These tasks can include running backups, updating databases, generating reports, and sending email reminders. In this article, we will discuss how to build a cron job using Node.js, a popular JavaScript runtime environment.

Node.js is an open-source, cross-platform JavaScript runtime that allows developers to build server-side applications using JavaScript. One of the key benefits of using Node.js for building cron jobs is that it can handle multiple concurrent connections and is highly scalable. This article will cover the basics of creating a cron job using Node.js, including setting up a schedule and running the job. We will also discuss some best practices for building and deploying cron jobs in a production environment. By the end of this article, you will have the knowledge and tools needed to build your cron job with Node.js.

What is a cron job?

A cron job is a scheduled task that runs automatically on a Unix-based operating system. The name "cron" is derived from the Greek word "Chronos" meaning time. Cron jobs automate repetitive tasks, such as sending emails, updating databases, and generating reports. They are typically run on a schedule, such as every day at a specific time or every hour.
Cron jobs are defined using a simple text file called the crontab which contains a list of commands to be executed and the schedule on which to execute them. Each line in the crontab represents a single cron job and follows a specific format. The format includes six fields, separated by spaces:

  1. The minute (0-59).
  2. The hour (0-23).
  3. The day of the month (1-31).
  4. The month (1-12).
  5. The day of the week (0-7, where both 0 and 7 represent Sunday).
  6. The command to be executed.

Cron job table

For example, the code snippet below illustrates how to schedule a task to run at every minute interval:

const cron = require("node-cron");

  cron.schedule("* * * * *", () => {
    console.log("running a task at every minute");
 })
Enter fullscreen mode Exit fullscreen mode

The first argument passed into the cron.schedule function is the cron expression. You use the expression to specify the time at which the job should run.
The asterisks used in the code above represent a different unit of time and are part of the crontab syntax. Using five asterisks (* * * * ) is the default crontab for scheduling a task every five minutes. A cron job can also be configured to run at more specific intervals using special characters such as asterisks () and commas (,). For example, an asterisk (*) in the hour field would run the command every hour, while a comma-separated list of values (e.g. "1,15,30") would run the command at the specified minutes.
The second argument is the function (job) that gets executed when the expression in the first argument is passed.
The node-cron schedule function has an optional third argument, the configuration object used for job scheduling. The code below illustrates what the optional argument should look like:

{
    schedule: true,
    timezone: "Asia/Kolkata"

 }
Enter fullscreen mode Exit fullscreen mode

The schedule by default is true, if you decide to set it to false, you’ll have to invoke the start method on the job object. A Job object is returned whenever the schedule function is called.
To execute the cron job, run the following command:

cron.start();
Enter fullscreen mode Exit fullscreen mode

Cron jobs are a powerful tool for automating tasks on a server, but they must be used with caution. Incorrectly configured cron jobs can cause system crashes or data loss. It's important to test cron jobs thoroughly before deploying them in a production environment and to monitor their performance regularly.

Benefits of using Node.js for cron jobs

Logo of Nodejs
Node.js is a powerful JavaScript runtime built on Chrome's V8 JavaScript engine, which has become increasingly popular in recent years for building web applications and other types of server-side software. One of the most significant benefits of using Node.js for cron jobs is that it allows developers to use JavaScript on the server-side, making it easy to integrate with other technologies and services.

Another advantage of using Node.js for cron jobs is its ability to handle asynchronous code execution. Node.js is designed to handle multiple requests asynchronously, which is essential for running cron jobs that may take a long time to complete. With its event-driven architecture, Node.js can handle these tasks without blocking the execution of other code, ensuring that the server remains responsive and can handle other requests.

One other benefit of using Node.js for cron jobs is its vast ecosystem of packages and modules. Node.js has an extensive library of modules that can be easily integrated into a cron job, such as the popular node-cron package, which provides a simple and flexible way to schedule tasks. This allows developers to quickly and easily build cron jobs without having to start from scratch.

Furthermore, Node.js has become a popular choice for building web applications and APIs, and it's easy to use the same codebase for both the web application and the cron job. This makes it easy to share data between the cron job and the web application and to leverage existing code and libraries.

Additionally, Node.js has a large and active community, which means that it's easy to find support and resources for building cron jobs. There are many tutorials, articles, and forums available that can help developers get started with building cron jobs using Node.js.

Furthermore, Node.js is an excellent choice for building cron jobs, due to its ability to handle asynchronous code execution, a vast ecosystem of modules and packages, easy integration with web applications, and large community support. With Node.js, developers can quickly and easily build powerful and reliable cron jobs that can automate repetitive tasks, such as sending emails, updating databases, and generating reports.

Setting up a cron job

The Node.js Package Manager (NPM) registry contains a very useful cron job package, node-cron that can be used to schedule jobs that run at specific intervals.

I assume you already know how to install and set up a Node.js development environment, click on the link to install and set up your Node.js development environment.

To get started with this tutorial, create a new project folder by running this command on your terminal:

mkdir project-folder-name
Enter fullscreen mode Exit fullscreen mode

On your terminal change the directory into the just created folder using the command below:

cd project-folder-name
Enter fullscreen mode Exit fullscreen mode

On the root of the folder run the command below:

npm init -y
Enter fullscreen mode Exit fullscreen mode

The command above creates amongst other files package.json file, which is useful for tracking your project dependencies and other necessary information.

Now install the node-cron package by running the command below:

npm i node-cron
Enter fullscreen mode Exit fullscreen mode

This will install the node-cron module in the project. Check your package.json file to confirm this is installed.

Next, build a Node.js server and use node-cron to schedule a task. Let’s say for this example, we want to print to the console this statement “Zenrow technical writer” every minute.
Create a new file, cronapp.js.

In your new cronapp.js file, require the node-cron module.

const cron = require("node-cron")

Enter fullscreen mode Exit fullscreen mode

Add the following lines of code to your cronapp.js file:

cron.schedule("* * * * *", () => {
    console.log("Zenrow technical writer");
 })
Enter fullscreen mode Exit fullscreen mode

To run the script, you're in the correct directory and run the command below:

node cronapp.js
Enter fullscreen mode Exit fullscreen mode

The expected output should look like seen below:

Zenrow technical writer
Zenrow technical writer
Zenrow technical writer
Zenrow technical writer
Zenrow technical writer
Zenrow technical writer
….
The output above represents what was printed to the console every minute before the server was stopped using CTRL C.

Sending Emails

Sending periodic emails is an important area of application for cron job. In this section, we will use the Node.js nodemailer and node-cron module to implement sending periodic email functionality. Nodemailer module support test account created with Ethereal Email.

To create a test account using Ethereal, click on the Create Ethereal Account button.

Ethereal test email

A test email will be generated automatically for you.

On your terminal, change the directory to the root folder using the command below:

cd project-folder-name
Enter fullscreen mode Exit fullscreen mode

Install nodemailer module using the command below:

npm i nodemailer
Enter fullscreen mode Exit fullscreen mode

Create a new file, cronEmail.js

Then require the necessary packages as shown below:

const cron = require("node-cron");
const nodemailer = require("nodemailer")
Enter fullscreen mode Exit fullscreen mode

Next, add the following code:

const transporter = nodemailer.createTransport({
    host: "smtp.ethereal.email",
    port: 587,


    auth: {
        user: "demoemail@ethereal.email",
        pass: "demopassword"
    }
 })
Enter fullscreen mode Exit fullscreen mode

The code above creates a mail transporter and sets the user and password.

NOTE: In live projects, you would use environment variables to store your password and any other sensitive information.

Next, add the following code snippet:

cron.schedule("24 13 * * *", () => {
    console.log("test")


    let data = {
        from: "demoemail@ethereal.email",
        to: "demoemail@ethereal.email",
        subject: "Test Email",
        text: "This is a test email"
    };


    transporter.sendMail(data, (err, info) =>{
        if(err){
            throw err;
        }else{
            console.log("Email sent");
        }
    })
 })
Enter fullscreen mode Exit fullscreen mode

The code snippet above schedules an email to be sent at (“24 13 * * *”), the pattern means emails will be sent at 1:24 pm every day. The code will send an email with the following contents:

Subject: “Test Email”
Text: “This is a test email”

To the Ethereal test email account.

We have covered how to use a cron job to schedule tasks, and send emails, the following section will illustrate how to delete files with a cron job. This use case becomes handy when you want to routinely delete a specific log file from the server at a particular interval.

Create a log file named:

zenrow.log

Then, add a message:

Zenrow logs

Create a new cronDelete.js file

Inside the cronDelete.js file, require the fileSystem (fs) and node-cron modules:

const cron = require("node-cron")
const fs = require("fs")
Enter fullscreen mode Exit fullscreen mode

Next, add the following code snippets:

cron.schedule("48 14 * * *", function() {
    console.log("Running Cron Job");
    fs.unlink("Zenrow.log", (err) => {
      if (err) throw err;
      console.log('Log file successfully deleted');
    });
  });

Enter fullscreen mode Exit fullscreen mode

The schedule pattern: “48 14 * * *”

  • Defines a value for minutes and hours as 48 and 14 respectively
  • It didn’t define the day
  • It didn’t define the day of the week or Month

Note: You can set the cron pattern to suit your needs.

Run the script with the following command:

node cronDelete.js
Enter fullscreen mode Exit fullscreen mode

The script will execute at 14:48PM and the zenrow.log will be deleted.

Some best practices for building and deploying a cron job

  • Test cron jobs thoroughly before deploying them to a production environment. This will help ensure that they are working as expected and won't cause any issues when they are in live environment.

  • Use a centralized logging system to collect and aggregate log data from cron jobs. This will make it easier to monitor and troubleshoot any issues that arise. You can learn more about how to use airplane to monitor cron jobs here.

  • Keep your cron jobs as simple as possible and do not include any unnecessary logic or functionality. This will help ensure that they are easy to maintain and debug
    .

  • Use a notification system to alert you when a cron job fails or when it completes successfully.

  • Use a monitoring tool to keep an eye on the performance and uptime of your cron jobs. This will help you quickly identify and resolve any issues that may arise.

  • Use a scheduler like Kubernetes cronjob to schedule the cron job, rather than using the built-in cron daemon. This allows for better scalability and fault tolerance.

Common issues with cron jobs

Cron jobs are a powerful tool for automating tasks on a server, but they can also come with some challenges and potential issues. Some of the most common issues with cron jobs include:

  • Lack of monitoring: If there is no proper monitoring, it may be difficult to detect when a cron job has failed or is not running correctly. This can lead to data inconsistencies or delays in completing important tasks.

  • Cron job failure: Cron jobs can fail for various reasons such as network issues, missing dependencies, or bugs in the code. It is important to have proper error handling and logging in place to detect and diagnose any issues that may arise.

  • Overlapping cron jobs: Another common issue is that multiple cron jobs scheduled to run at the same time can lead to resource conflicts and potential data inconsistencies.

  • Security risks: Cron jobs can also pose security risks if not properly configured. For example, a cron job that runs with root permissions can be exploited by malicious actors to gain access to sensitive information.

Strategies for troubleshooting cron jobs

Troubleshooting cron jobs can be a challenging task, but with the right strategies, you can quickly identify and resolve any issues. Here are some strategies for troubleshooting cron jobs:

  • Check the cron log: Most systems have a log that records when cron jobs run and any errors that occur. The location of the log file varies depending on the operating system.

  • Check the cron schedule: Make sure that the cron schedule is correct and that the job is scheduled to run at the correct time.
    Check the environment variables: Some cron jobs rely on environment variables, so make sure that the necessary environment variables are set and that they have the correct values.

  • Before deploying to production, test the script manually: Try running the script manually from the command line to see if it runs correctly and to check for any errors.

  • Check for dependencies: Ensure that all necessary dependencies for the command or script specified in the cron job are installed and configured correctly.

  • Schedule the job with different intervals: Try scheduling it with different intervals, like every minute or every 5 minutes, to check if it works fine.
    By following these strategies, you can quickly identify and fix problems with your cron jobs, ensuring that they run smoothly and efficiently.

Conclusion

Building a cron job with Node.js is a simple and efficient way to automate repetitive tasks in your applications. By using the node-cron package, you can easily schedule tasks to run at specified intervals, making it easy to keep your applications running smoothly. This article has provided a step-by-step guide for building a cron job with Node.js, including code snippets, and also discussed the strategies for troubleshooting cron jobs. With this knowledge, you can now easily automate tasks in your Node.js applications, freeing up valuable time and resources.

Top comments (0)