Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node JS Mail scheduler

I am working on an Angular(frontend) and NodeJS(APIs) application. I want to schedule email on particular dates without any external call. I explored node-schedule. But how should I ensure that it runs forever in my NodeJs APIs? Like where should I put the code - in app.js or give it a route?

like image 634
Divesh Soni Avatar asked Aug 11 '26 17:08

Divesh Soni


2 Answers

You are on the right track. You have to use cron service for this. And node-schedule is a good choice for this.

So first, make a file named email-service.js.

Inside that put your logic.

email-service.js

var node = require('node-schedule');

var sendEmail = node.scheduleJob('0 6 * * *', function(){
   console.log('Starting..');
   init(); // write your logic here to send email
});

function init() {
  console.log('Your logic goes here.');
}

module.exports = {
    cronService: cronService
}

app.js

In the app.js import email-service.js.

const emailService = require('email-service')

emailService.sendEmail.start(); // start service..

You can schedule a cron accordingly. Below is the format of the cron.

The cron format consists of:

*    *    *    *    *    *
┬    ┬    ┬    ┬    ┬    ┬
│    │    │    │    │    │
│    │    │    │    │    └ day of week (0 - 7) (0 or 7 is Sun)
│    │    │    │    └───── month (1 - 12)
│    │    │    └────────── day of month (1 - 31)
│    │    └─────────────── hour (0 - 23)
│    └──────────────────── minute (0 - 59)
└───────────────────────── second (0 - 59, OPTIONAL)
like image 183
Surjeet Bhadauriya Avatar answered Aug 14 '26 12:08

Surjeet Bhadauriya


One more thing, if the application is restarts then your schedule event get cancelled. so it might be a good approach if you save your event in a db and marked them complete or incomplete. And re-schedule your incomplete events at the restart of the application.

I use this to make sure all events runs.

like image 43
Pankaj Jindal Avatar answered Aug 14 '26 11:08

Pankaj Jindal