How to send email after a one week in nodejs - node.js

I created a script: when a user signups our app, then I will send a welcome email, then I want after one another will be send.
Note: Now cron job runs every minute, I will change it later.
var job = new CronJob('* * * * *', function() {
console.log('Cron Job is happen on',Date());
emailSend()
}, null, true, '');
function emailSend(){
SingUpDate = something
comapredate = today-7
if(comparedate == signupdate){
sendEmail()
}
else{
return false
}
}
I want to know about how to stop cron after a week.

You could have your emailSend function remove its own cron job:
var job = new CronJob('* * * * *', function () {
console.log('Cron Job will happen on', Date())
emailSend()
}, null, true, '')
// you will need to start the job:
job.start()
function emailSend () {
SingUpDate = something
comapredate = today-7
if (comparedate == signupdate) {
sendEmail()
// and then stop it here:
job.stop()
} else {
return false
}
}
Or you can schedule it for the specific date that you want:
const date = new Date();
date.setDate(date.getDate() + 7)
const job = new CronJob(date, () => {
console.log(`Scheduled job for ${date} running at ${new Date()}`)
emailSend()
}, null, true, '')
job.start()

Related

How to run cron job only when making a get request & not everytime we start the server

I want the cron job to get triggered only when we make a get request, it does for the first time, but if I save it will re-run again.
The code does not run whenever the server starts or restarts but as soon as I hit that specefic endpoint, It will run every time the server re-starts.
startTime = new Date().getTime();
numberOfMinutes = 10;
#Cron(CronExpression.EVERY_MINUTE, {
name: 'myJob',
})
async getParisAirQuality() {
this.logger.verbose(`Getting paris air quality`);
const result = await this.getCityAirQuality({
latitude: '48.856613',
longitude: '2.352222',
});
const airQuality = new this.airQualityModel({
result,
datetime: new Date().toLocaleString(),
});
await airQuality.save();
this.closeJob();
return {
result: airQuality.result,
datetime: new Date().toLocaleString(),
};
}
closeJob() {
const job = this.schedulerRegistry.getCronJob('myJob');
const endTime = this.startTime + 1000 * 60 * Number(this.numberOfMinutes);
if (job.lastDate().getTime() >= endTime) {
job.stop();
}
}

Nodejs - How to set cron job to run on every 2 Sunday

Below cron job runs every Sunday 14:35:00, but I want to run the run job every 2 Sunday 14:35:00.
Is it possible to do that?
var CronJob = require('cron').CronJob;
new CronJob('0 35 14 * * 0', async function () {
}, null, true, 'America/Los_Angeles');
I didn't see any pattern for your requirement, but you can this
var CronJob = require('cron').CronJob;
var x = 1;
new CronJob('0 35 14 * * 0', async function () {
if (x / 2 != 1) {
x++;
//do somthing
} else {
x = 1;
}
}, null, true, 'America/Los_Angeles');

Agenda not running jobs on schedule

I am trying to use agenda to schedule jobs at a certain date and time, but the jobs are not running when the specified date is reached.
This is how I'm creating the job:
agenda.create(type, data)
.schedule(new Date(startDate))
.repeatEvery('11 21 * * *', {timezone: 'Europe/Bucharest'})
.save();
This is how I start agenda:
const Agenda = require('agenda');
const mongoDB = process.env.DB_PATH;
const mongoConnectionString = mongoDB;
let agenda = new Agenda({db: {address: mongoConnectionString, collection: 'jobs'}});
let jobTypes = process.env.JOB_TYPES ? process.env.JOB_TYPES.split(',') : [];
jobTypes.forEach(function(type) {
require('./jobs/' + type)(agenda);
});
if(jobTypes.length) {
agenda.on('ready', function() {
console.log('agenda start')
agenda.start();
});
}
function graceful() {
agenda.stop(function() {
process.exit(0);
});
}
process.on('SIGTERM', graceful);
process.on('SIGINT' , graceful);
export default agenda;
This is an example with a job that didn't start on the scheduled date:
Is there something I'm doing wrong?
EDIT:
The job is triggered if I do schedule(new Date()), but it won't using a defined date.

Nested cron job stop and start issue

I want to start two jobs simultaneously, but after some time i will stop one of them and will continue second one.
In our case i am starting 2 jobs every 30 seconds and each jobs itself execute every 4 second, If i stop first job in the middle of execution, it will stop and second job is performing its task but the problem is that after 30 second first job also start performing task even though we have stop that job.
Here Is my Code:
var job1;
var job = new CronJob({
cronTime: '*/30 * * * * *',
onTick: function () {
var interval = 4000;
var index = 0;
var index1 = 0;
var users = ['U1', 'U2', 'U3', 'U4']
var users1 = ['D1', 'D2', 'D3', 'D4']
job1 = new CronJob({
cronTime: '*/4 * * * * *',
onTick: function () {
var user = users[index];
console.log("Sent To :" + user);
index++;
if (users.length == index) {
job1.stop();
}
},
start: false,
timeZone: 'GMT'
});
job1.start();
var job2 = new CronJob({
cronTime: '*/4 * * * * *',
onTick: function () {
var user = users1[index1];
console.log("Sent To :" + user);
index1++;
if (users1.length == index1) {
job2.stop();
}
},
start: false,
timeZone: 'GMT'
});
job2.start();
},
start: false,
timeZone: 'GMT'
});
job.start();
For stop job:
job1.stop();
Your first job starts is just because you have set the cron to run both the jobs at every 30 sec which is what I can see from your code. This will keep on running your whole bunch of stuff to run every 30 sec.

node-schedule is not work at time

i want to use node-schedule , i get information from Data Base every day , and for each item i want to do some thing at special time.
this is my code :
users.forEach(function(users_entry){
if(err){
console.log(err);
}
else{
var date = new Date(2014, 11, 29, 11, 45, 0);
schedule.scheduleJob(date,
function(){
console.log('The world is going to end today.');
});
}
});
but above code doesn't run at mentioned time and works all the time.
what is problem?
i changed my code and used cron.
https://www.npmjs.org/package/cron
it works very well :)
var CronJob = require('cron').CronJob;
new CronJob('* * * * * *', function(){
console.log('You will see this message every second');
}, null, true, "America/Los_Angeles");
try this
var CronJob = require('cron').CronJob;
var job = new CronJob('00 00 12 * * 1-7', function() {
/*
* Runs every day
* at 12:00:00 AM.
*/
}, function () {
/* This function is executed when the job stops */
},
true, /* Start the job right now */
timeZone /* Time zone of this job. */
);
Try this:
const schedule = require('node-schedule');
const moment = require('moment');
const rule = scheduled.RecurrenceRule();
let time = '2021-07-30 14:20:00';
rule.tz = 'Asia/Kolkata';
rule.year = moment(time).year();
rule.month = moment(time).month();
rule.date = moment(time).date();
rule.hour = moment(time).hours();
rule.minute = moment(time).minutes();
rule.second = moment(time).seconds();
schedule.scheduleJob(rule, async function () {
console.log("Scheduled")
});

Resources