DEV Community

Cover image for Cron Job: Node Js
Abayomi Ogunnusi
Abayomi Ogunnusi

Posted on • Updated on

Cron Job: Node Js

Experience is the mother of all teachers, as they say. (...Anonymous)

I was assigned a small project to do.
It was about a prediction app that needed to be able to update its fixtures on the go.

🌳 I was advised by a senior back-end developer to use the cron job concept or the worker process.

We want to write a task scheduler in a nutshell. Here's how to use Node Js to run simple task scheduler.


  • Install node-cron : npm install node-cron

  • Install shell for windows : npm install shelljs --> This is a Unix shell commands for Node.js

So let's write a simple function that runs every seconds

const cron = require("node-cron");
let shell = require("shelljs");

cron.schedule("* * * * * *", () => {
  if (shell.exec("dir").code !== 0) {
    console.log("Something went wrong");

Enter fullscreen mode Exit fullscreen mode

Image description

Send automated emails with Node-Cron
let cron = require('node-cron');
let nodemailer = require('nodemailer');
let shell = require('shelljs');

// e-mail message options
let mailOptions = {
  from: 'enter your mail here',
  to: 'enter receipient's email here',
  subject: 'Email from Node-App: A Test Message!',
  text: 'Some content to send',

// e-mail transport configuration
let transporter = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: 'your user email here',
    pass: 'Your password here',

cron.schedule('* * * * *', async () => {
  // Send e-mail
  await transporter.sendMail(mailOptions, function (error, info) {
    if (shell.exec('dir').code !== 0) {
      console.log('Something went wrong');
    if (error) {
    } else {
      console.log('Email sent: ' + info.response);
Enter fullscreen mode Exit fullscreen mode

Thanks fro reading....


Node cron

Top comments (1)

oglord1 profile image

Hi Abayomi,
How can I use this node-cron to automate and execute my node.js script in another dir?
please help me!