My cluster and cron are working but problem is that cron is being called multiple times because of cluster, how to i call it only once?
Here is my cluster file:
let cluster = require('cluster')
if(cluster.isMaster){
let cpu = require('os').cpus().length
for(let i = 0; i < cpu; i++){
cluster.fork()
}
console.log('Cluster server started, Thread: '+cpu)
cluster.on('exit', function(){
console.log('CPU die start again.')
cluster.fork()
});
} else {
require ('./router.js')
}
this is my cron file:
const CronJob = require('cron').CronJob;
const tweetsControl = require('../modules/tweetsControl')
var job = new CronJob('*/10 * * * * *', async () => {
console.log('Cron enabled')
console.log('Running tweetsControl.fetchTweets')
await tweetsControl.fetchTweets().then((res) => {
console.log(`End tweetsControl.fetchTweets (${res})`)
})
}, null, true)
job.start()
and cron is included in my router.js
const cron = require('./node-cron/cron')
Related
I am trying to send a scheduled notification with the node-cron library and it is working fine in my local system but after deploying the codes to the Heroku server it is not working.
const triggerPushNotification = (notifiction, startMinutes, startHour) => {
console.log('Checked Trigger Push Notification Function ...');
cron.schedule(`${startMinutes} ${startHour} * * *`, async () => {
console.log('Checked Inner Cron ...');
await notificationHelper.pushNotification(notifiction.receiversTokens, notifiction.notificationTitle, notifiction.notificationBody, notifiction.notificationURL, notifiction.notificationImage);
});
};
cron.schedule('*/55 * * * * *', async () => {
console.log('Checked Outer Cron ...');
const notifiction = await notificationHelper.viewScheduledNotification();
const formattedStartDate = `${notifiction.startDate}`;
const formattedEndtDate = `${notifiction.endDate}`;
const fullTodayDate = new Date();
const fullEndDate = new Date(formattedEndtDate);
const fullStartDate = new Date(formattedStartDate);
const startHour = notifiction.time.split(':')[0];
const startMinutes = notifiction.time.split(':')[1];
if (fullStartDate <= fullTodayDate && fullTodayDate <= fullEndDate) {
console.log('Checked Middle Cron ...');
console.log(startHour, ':', startMinutes);
triggerPushNotification(notifiction, startMinutes, startHour);
}
});
It is possible to kill a cluster worker that is running an infinite loop? I've tried, but unable to kill the worker. I guess the kill command cannot get onto the worker's js event loop. Any ideas on how else I can do this? When the master receives a "start" message, I want it to fork a worker. When the master receives a "stop" message, I want it to kill the worker.
const cluster = require('cluster');
const numCPUs = require('os').cpus().length;
const process = require('process');
const { nrpin, nrpout } = require("./helpers/PubSub");
const chalk = require('chalk');
//https://leanpub.com/thenodejsclustermodule/read
//https://gist.github.com/jpoehls/2232358
const arrWorkers = [];
if (cluster.isMaster) {
masterProcess();
} else {
childProcess();
}
function masterProcess() {
console.log(chalk.blueBright(`Master ${process.pid} is running`));
nrpin.on("start", async (bot) => {
console.log("Start:", bot._id);
if (arrWorkers.length == numCPUs){
console.log(chalk.yellowBright("No CPUs available to create worker!"));
}
const worker = cluster.fork();
arrWorkers.push({
workerId: worker.id,
botId: bot._id
})
})
nrpin.on("stop", async (bot) => {
console.log("Stop:", bot._id);
const worker = arrWorkers.find(x => x.botId == bot._id);
if (worker){
console.log("killing worker:", worker.workerId);
cluster.workers[worker.workerId].kill();
}
})
// Be notified when workers die
cluster.on('exit', function(worker, code, signal) {
if (worker.isDead()) {
console.info(`${chalk.redBright('worker dead pid')}: ${worker.process.pid}`);
}
});
}
function childProcess() {
console.log(chalk.green(`Worker ${process.pid} started...`));
while(true){
console.log(Date.now());
}
}
Never mind, I solved this using process.kill
let process_id = cluster.workers[worker.workerId].process.pid;
process.kill(process_id);
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.
On init of my application i start function with settings.
const schedule = require('node-schedule');
const monk = require('monk');
const db = monk(config.mdbConnect);
var TGusers = db.get('TG-users');
...
...
TGusers.find({'cron.status': true}, {chatid:1, cron: 1})
.then((users) => {
console.log('twise');
for(var i=0;i<users.length;i++){
cronbox[users[i]] = {};
cronbox[users[i]].reminder = schedule.scheduleJob('*/1 * * * *', function(chatid){
console.log('chatid = '+ chatid);
tg.api.sendMessage(chatid, '🐳 Nuclear launch detected! / ' +chatid,
{'parse_mode': 'Markdown'}
);
}.bind(null, users[i].chatid));
}
}).catch((err) => {
if(err) saveerr(err);
}).then(() => db.close())
And this Monk find finction fired twice. I got two "twice" in my console, and .. looks like two cron tasks... What I did wrong?
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")
});