What are cron jobs and what does node-cron do ?

Ashish Kasama|6/22/2022, UTC|14 MIN READ|
Play
//What are cron jobs and what does node-cron do ?

Share

 

INTRODUCTION

Do you need to run a script regularly but don't want to remember to do so? Perhaps you need to run a task at a specified time or intervals but don't want it to consume all of your CPU or storage. Cron jobs are ideal for the work in either situation. Let's take a look at what they are, how to use them, and what you can do with them.

There are instances when it is necessary to conduct a series of tasks constantly at a future date and time. These duties are usually administrative, although they could include anything from database backups to email downloads when everyone is sleeping.

Cron is a Unix-like operating system's time-based job scheduler that performs activities in the future. The word "Chronos" is derived from the Greek word "χρόνoς “(Chronos), which signifies "time."

Vixie Cron is the most often used version of Cron. It was created in 1987 by Paul Vixie.

Job Terminology in Cron

A job is a unit of work that consists of a series of actions to complete a task. Sending out emails to a group of users, for example. The terms task, job, cron job, and event will all be used interchangeably in this text.

A daemon is computer software that runs on a server and performs various tasks. Daemons frequently start when the computer boots up. A web server is a system that handles HTTP requests. Cron is a daemon that does tasks regularly.

A cron job is a job that is run regularly. When the work is due, the daemon executes it.

Web cron is a server-based work scheduler that runs at specific times. It's a replacement for Cron, which is frequently used on shared web hosts that don't give shell access.

Every developer sooner or later faces a problem when it comes to dealing with cron jobs.

No developer wants to spend all their time on tedious tasks such as system maintenance and administration, daily database backup, and downloading files and emails at regular intervals.

That’s where task scheduling comes into the picture.

Task scheduling enables you to schedule arbitrary code (methods/functions) and commands to be executed at a fixed date and time, at recurring intervals, or once after a specified interval.

Task scheduling is often handled by utility services such as cron at the OS level. For the node js app, we have packages that can handle scheduling jobs. This functionality is implemented using packages such as node-cron, which bills itself as a “tiny task scheduler in pure JavaScript for NodeJS.”

 Let’s understand how node-cron works:

The node-cron module permits you to schedule tasks in Node using the complete crontab syntax.

Crontab is a type of string syntax composed of six asterisks (*)

Allowed fields 

Allowed cron values include the following.

Field

Value

second

0–59

minute

0–59

hour

0–23

day of the month

1–31

month

1–12 (or names)

day of the week

0–7 (or names, 0 or 7 are Sunday)

 

Let’s go for code,

First of all, you need to setup Node js in your system.

After that Install node-cron using npm.

npm install --save node-cron

Task scheduling syntax

Options

  • scheduled: A Boolean to set if the created task is scheduled (default is true)
  • time zone: The time zone used for job scheduling

 Take a look at the following example.

Create task.js

 

Now you can schedule tasks as per your requirement

The asterisks (*) in positions, two, three, four, five, and six of the time specification are like file globs, or wildcards, for time divisions; they specify “every minute,” “every hour,” “every day of the month,” “every month,” and “every day of the week,” respectively.

 

 You can explore more options at https://www.npmjs.com/package/node-cron

And you can create different time schedule using https://crontab.guru here you can explore more options for cron.

How to Stop a task

Pros and Cons of node cron

Node cron is very convenient and flexible. Let's take a real-life example to understand its work.

Suppose we have a requirement to generate a total sale of every hour for an analyst of an e-commerce site selling.

Here in this scenario, we have certain task that will run after every hour and display or store that data so we will use cron scheduler.

Now, these functions run after every hour and store sell data.

But wait what if we mistakenly execute this code two times?

In this case this will execute 2 times and same output will store two times and  generate duplicate records

This script never ends, it acts as a daemon. This solution doesn’t depend on infrastructure, it can be run anywhere including Docker. You can also combine several cron jobs in one script and you can create new cron jobs dynamically in runtime.

It’s very convenient and flexible, but like in the previous solution, you need to make sure that your app is executed only in one instance.

Safety with node-cron

  1. You need to make sure that your app executes only once, when you have cron function in it.
  2. When you have database connection in cron job then you must make sure that you are using pooled connection instead of normal connection otherwise your connection time out after a certain period of time.
  3. To handle errors always manage try-catch with cron function otherwise your cron will be stopped if error occurs.

Other task schedulers?

We have task scheduler like  Agenda, Node-schedule, Node-cron, Bree, Cron, and Bull  for the Node runtime environment.

Let’s take brief about every job schedulers.

Agenda

Agenda is an MIT-licensed scheduler for Node. 

Agenda offers functionality for flexibly scheduling jobs using both cron and a more human-readable syntax. To utilize Agenda as a job scheduler, you'll need a working MongoDB database.

Minimal overhead is provided by the agenda. 

Agenda seeks to maintain its code base as compact as possible

  1. Mongo-backed persistence layer.
  2. Promises-based API.
  3. Scheduling with configurable priority, concurrency, repeating, and persistence of job results.
  4. Scheduling via cron or human-readable syntax.
  5. Event-backed job queue that you can hook into. 

Node-schedule

This is another MIT-licensed open-source package for Node job scheduling.

Node-schedule is mostly used for time-based scheduling instead of interval-based scheduling, however, it can be used in both cases. You may simply schedule a job to run on certain dates with the Node-optional schedule's recurrence configuration.

Bree

Bree is another MIT-licensed JavaScript job scheduler. It works in both Node and the browser. It provides support for concurrency, throttling, long-running jobs, and much more. Check the documentation for a full list of features.

Bull

Bull is a Redis-based queue system for Node that requires a running Redis server.

Bull offers features such as cron syntax-based job scheduling, rate-limiting of jobs, concurrency, running multiple jobs per queue, retries, and job priority, among others. Check the manual for a complete list of features.

Live example where we have utilized a job scheduler. 

  1. POS System Aryamond

In the POS system, we have a requirement to generate a transaction file in text format daily and that file contains hourly records of the total sales of Shopify from the POS system.

Final Thoughts

Cron is a daemon that keeps track of events that are planned to happen in the future. These jobs are defined in crontab files, which are special configuration files. If users are authorized to use Cron, they can have their crontab file depending on the /etc/cron. Allow or /etc/cron.deny files. Cron also loads system-wide cron jobs, which have a slightly different syntax than user-level cron jobs.

Node-cron makes scheduling a task for a specific time interval a breeze. It also has a variety of other settings that give it some interesting applications. 

A well-known provider of software and digital solutions is Lucent Innovation.
We make an effort to stay current with technological developments in order to better our company culture and provide more profitable outcomes.
Our expertise in e-commerce development is extensive. We deliver one-of-a-kind solutions for our customers that lead to increased efficiency, growth, and profitability. Additionally, we create, install, and expand functional e-commerce websites.

Employing experts as online and mobile app development soars to new heights every year, Node js has recently been a benefit for many enterprises. To support your business requirements, our developers create, develop, and install web-based server side programmes. For the development of complicated apps for small to large businesses, hire Node.JS developers from us.


Key Takeaway

Explore the world of task scheduling with cron jobs and node-cron in Node.js applications. Learn about the basics of cron jobs, their role in repetitive tasks, and how node-cron simplifies scheduling. Discover other job schedulers like Agenda, Node-schedule, Bree, and Bull, and gain insights into real-world applications. 

Q: What is the purpose of cron jobs?

A: Cron jobs are designed to execute tasks at specified times or intervals, automating repetitive actions such as system maintenance, database backups, and more.

Q: How does node-cron work in Node.js applications?

A: Node-cron, a JavaScript module, facilitates task scheduling in Node.js using the complete crontab syntax. Developers can schedule tasks at specific intervals, dates, or recurring patterns, enhancing the automation of processes.

Q: What are the pros and cons of using node-cron for task scheduling?

A: Node-cron offers flexibility and convenience, allowing developers to schedule tasks with ease. However, developers need to ensure that their app runs only once, manage errors with try-catch blocks, and use pooled connections for databases to maintain reliability.

Q:Which other task schedulers are available for Node.js?

A: Several task schedulers, including Agenda, Node-schedule, Bree, Cron, and Bull, cater to the Node.js runtime environment. Each has unique features and use cases, providing developers with options based on their requirements.

Q: Can you provide a real-world example of task scheduling in a POS system using a job scheduler?

A: In a Point of Sale (POS) system named Aryamond, a job scheduler is utilized to generate a daily transaction file containing hourly records of total sales from Shopify. This demonstrates the practical application of task scheduling in a business scenario.

Also, read - Node.js for Startups: Ignite Innovation, Scale Rapidly, and Dominate the Market

Ashish Kasama

Looking for

Development

Solutions?

Lets Discuss
Lucent innovation
We are a family filled with talented experts that help global brands, enterprises, mid-size businesses or even startups with innovative solutions.
Newsletter
Accelerate your tech projects with us. Get in touch with us.
Follow us
facebooklinkedinyoutubeinstagramtwitter
lucent innnovation: cltuch

Lucent Innovation, © 2024. All rights reserved.Privacy policyDMCA compliant image