0

I'm trying to send an email to the user periodically(daily, weekly, monthly) based on their preference from my nodejs application using node-cron. Here, user can edit/change their mail preference(weekly, daily..etc). so when they do, the cron expression gets updated to match their preference from the backend.

However, the previous preference still getting triggered, I believe that we have to destroy the previous job. how to do it?

Is this the right approach for my problem? or Do I need to store their preferences in database and triggered the mails manually based on the date?

Apoorva Chikara
  • 8,277
  • 3
  • 20
  • 35
ajay
  • 328
  • 1
  • 5
  • 17
  • Are you stopping the previous cron-job ? These jobs are specifically set to the user (Admin) preference or set globally for everyone? – Apoorva Chikara May 17 '21 at 11:36
  • 1. No, not stopping the previous job. is there any way we can stop job with id so that I can store it on db and when new preference come in, I can delete older one? 2. jobs are set to the user preference only. – ajay May 17 '21 at 11:53

1 Answers1

0

This is how you should do it with node-cron :

const cron = require('node-cron');

const task = cron.schedule('* * * * *', () =>  {
  console.log('stopped task');
}, {
  scheduled: true
});

task.start();
task.stop();
task.getStatus(); // get you the status, so for every user check it and then restart it.
task.destroy();  // it will kill the job 

It doesn't give any ID, but you can check the processID and store it anywhere.

You can check here for documentation.

Apoorva Chikara
  • 8,277
  • 3
  • 20
  • 35