Published on

How to Create a Scheduler Service in Node.js?

Authors

What is a Scheduler Service?

A scheduler service provides the ability to execute tasks at specific times or intervals.

How to Write a Node.js Scheduler Service?

You can write a scheduler service in most modern frameworks, such as .NET Core, Elixir, Node.js, Go, etc.

In this example, I will use Node.js. To follow this example, you need to have basic knowledge of JavaScript.

Take the following steps to create a basic scheduler service:

1. Create a Project Folder for Your Service

mkdir scheduler-service && cd scheduler-service

2. Initialize npm

npm init -y

3. Install the Following Packages:

  • node-schedule
  • log4js

I chose the node-schedule package for cron-like scheduling functionality and log4js for logging.

4. Create a JavaScript File

  • Example: schedule.js

5. Import the node-schedule Library and Assign a Job to the scheduleJob Function

const schedule = require('node-schedule')

const job = schedule.scheduleJob('*/1 * * * *', function () {
  console.log('Every minute, you will see this log.')
})

As you can see in the example above, scheduleJob has two parameters:

1. Cron Expression

Cron expressions are used to initialize a repetitive time for a job. It is a string consisting of six or seven subexpressions (fields) that describe individual details of the schedule.

┬    ┬    ┬    ┬    ┬    ┬
│    │    │    │    │    │
│    │    │    │    │    └ Day of week (0 - 7) (0 or 7 is Sunday)
│    │    │    │    └───── Month (1 - 12)
│    │    │    └────────── Day of month (1 - 31)
│    │    └─────────────── Hour (0 - 23)
│    └──────────────────── Minute (0 - 59)
└───────────────────────── Second (0 - 59)

2. A Function

This function defines the task that we want to schedule.

Here is the complete JavaScript code that uses log4js to log:

const log4js = require('log4js')

log4js.configure({
  appenders: { log: { type: 'file', filename: 'schedule.log' } },
  categories: { default: { appenders: ['log'], level: 'info' } },
})

const logger = log4js.getLogger('log')

logger.info('Scheduler started.')
const job = schedule.scheduleJob('*/1 * * * *', function () {
  logger.warn('Every minute, you will see this log.')
})

How to Write a systemd Service File

To register our service with the Linux service manager, we need to create a systemd service file.

Take the following steps to create a systemd service file:

1. Type the Following Command in the Linux Terminal

vi /etc/systemd/system/schedule.service

2. Put the Following Content in It

[Unit]
Description=Node Service

[Service]
WorkingDirectory=/home/emin/node/
User=ubuntu
ExecStart=/usr/bin/node /home/ubuntu/hello_env.js
Restart=on-failure
RestartSec=10

3. Run sudo systemctl daemon-reload

You must do this whenever any of the service files change at all so that systemd picks up the new information.

4. Start the Service

sudo systemctl start schedule

5. Check the Status of the Service

sudo systemctl status schedule

This command shows the status of the service.

After starting your service, you should see a schedule.log file in the location of the service.

Resources: