Friday, February 18, 2022

[SOLVED] How to manage Cron Jobs in Node.js

Issue

Is there any node.js library that allows you to create n number of cron jobs providing some sort of key and then having the possibility to remove/edit a particular job by key?

For example, I'm looking for something like this:

import cronManagerLibrary from 'library';

export const startJob = (key) => {
  cronManagerLibrary.addJob(key, '10 * * * * *', function);
}

export const removeJob = (key) => {
  cronManagerLibrary.removeJob(key);
}

export const updateJob = (key) => {
  cronManagerLibrary.updateJob(key, interval);
}

export const listJobs = () => {
  cronManagerLibrary.list();
}

UPDATE:

I've found this library cron-job-manager that does exactly what I need, but I'm not sure how to persist the list of jobs since I need to create a job manager object every time...

This is what I've tried:

import CronJobManager from 'cron-job-manager';

export startJob = (key) => {
  const manager = new CronJobManager();
  taskFunction = () => {
    console.log('CRON JOB RUNNING');
  }
  manager.add(key,'10 * * * * *', taskFunction);
  manager.start(key);
  console.log(manager);
}

Every time I call the startJob function in order to create a new cron job the manager object will not keep the previous started job... is there a way to handle that?


Solution

You can use cron module to do this. Install cron using npm i cron. As an example,

var CronJob = require('cron').CronJob;

new CronJob('* * * * * *', function () {
    console.log('You will see this message every second');
}, null, true, 'America/Los_Angeles');

See documentation for more info,

If you want to do more cron activities you can always use any terminal commands. See below example,

var exec = require('child_process').exec;

exec("crontab -l", function(err, stdout, stderr) {
    console.log(stdout);
});


Answered By - Janith
Answer Checked By - Mary Flores (WPSolving Volunteer)