CronJob executing only once - node.js

I'm using CronJob for NodeJS https://github.com/kelektiv/node-cron
I don't understand why but my CronJob is running only once. It is supposed to run once every 10 seconds but after the first run it doesn't restart.
async function Job(moneda, condicion) {
console.log('init');
var res = await Analyzer.GetSpread(moneda);
var spread = res.MaxExchange.Bid/res.MinExchange.Ask;
console.log('Spread: ' + spread + 'Moneda: ' + moneda);
if (await condicion.CumpleCondicion(spread)){
var ids = await db.GetSuscripciones();
var mensaje = 'Spread: ' + spread.toFixed(3) + '\nMenor Ask: ' + res.MinExchange.Exchange + '--> ' + res.MinExchange.Ask + '\nMayor Bid: ' + res.MaxExchange.Exchange + '--> ' + res.MaxExchange.Bid;
for (var i = 0, len = ids.length; i < len; i++) {
bot.SendAlert(ids[i].id,mensaje);
}
}
console.log('end'); //this is reached
}
exports.Start = function(value){
condicionBTC = new condicionState('btc');
new CronJob('*/10 * * * * *', Job('btc',condicionBTC), null, true, 'America/Los_Angeles');
}
And this is printed in the console (only once)
init
Spread: 1.007141110114658 Moneda: btc
cumple condicion 1.007141110114658
end
If there's some exception stopping the cron job, where should I catch it so I can see what's going on?
I've added this
var job = new CronJob('*/10 * * * * *', Job('btc',condicionBTC), null, true, 'America/Los_Angeles');
setInterval(function(){ console.log(job.running); }, 3000);
and keeps printing true

Your cron pattern is wrong. According to https://github.com/kelektiv/node-cron :
"this library has six fields, with 1 second as the finest granularity."
Seconds: 0-59
Minutes: 0-59
Hours: 0-23
Day of Month: 1-31
Months: 0-11 (Jan-Dec)
Day of Week: 0-6 (Sun-Sat)
So your cron pattern is trying to run every 10th of a second, which is not possible.
Try replacing your cron pattern with '10 * * * * *'

Related

Node-Cron: how to ensure last job is complete

I am using node-cron to send operational emails (currently searching for new emails that need to be sent every minute).
My function (operationalEmails) looks for mongodb records that have a sent flag = false, sends the email, then changes the sent flag = true.
If an iteration of the cron has a large payload of records to send, it could take more than a minute.
How do I ensure the last iteration of the cron is complete before starting a new one?
//Run every Min
cron.schedule("* * * * *", () => {
operationalEmails();
});
you would need to create a simple lock
const running = false;
function operationalEmails() {
if (running) {
return
}
running = true;
// do stuff
running = false;
}
//Run every Min
cron.schedule("* * * * *", () => {
operationalEmails();
});

How to let muliple people use the command at the same time

So I made a bot and one of the commands reqiures it to wait. While someone else is using that how do I let another user, use that command as well and not wait until the other person is finished?
if(command ==='rm'){
var hithere2 = message.content
var ret = hithere2.replace('-rm ','');
var result = ret.slice('&').split(',');
let remindercontent = result[0]
let remindertime = result[1]
if(!isNaN(remindertime)){
if(remindertime % 1 == 0){
message.channel.send({embed: {
color: Math.floor(Math.random() * 16777214) + 1,
title: "Reminder set for " + remindercontent,
description: 'It will go off in ' + remindertime + ' seconds',
}})
let sleeptime = remindertime * 1000
sleep(sleeptime);
message.channel.send('<#' + message.author.id + '>')
message.channel.send({embed: {
color: Math.floor(Math.random() * 16777214) + 1,
title: `BEEEP`,
description: `${remindertime} seconds ago you wanted to remind yourself to **${remindercontent}**`,
}})
}
}else {
message.channel.send('Please enter a valid number after the comma!');
}
Above is the command for the thing that I need to run simultaneously. I have the system-sleep mudule installed.
Have you tried the setTimeout function? I'd usually consider using sleep() functions like that bad practise since you're stalling the thread.
Something like this might work for you (haven't tried this, you may need to pass arguments to that function):
setTimeout( function() {
message.channel.send('<#' + message.author.id + '>')
message.channel.send({embed: {
color: Math.floor(Math.random() * 16777214) + 1,
title: `BEEEP`,
description: `${remindertime} seconds ago you wanted to remind yourself to
**${remindercontent}**`,
}})
}, sleeptime);
To show what a mean jj, here's a code snippet as an example:
var commentInXMilliseconds = (delay) => {
const text = "New time";
setTimeout( function() {
console.log(`${text} ${new Date()}`);
}, delay);
}
console.log(`Start time: ${new Date()}`);
commentInXMilliseconds(2000);

How Can I Console.log countdownjs module via node.js

I'm using countdownjs module
, How Can I Console.log countdownjs for 3 days later, via node.js?
Here is a small example how you can use the countdown module:
var now = new Date();
var durationInDays = 3;
var durationInMilliseconds = (durationInDays * 24 * 60 * 60 * 1000);
var future = now.getTime() + durationInMilliseconds;
var countdownInfo = countdown(now, future);
// print it once
console.log(countdownInfo.toString());
// print it every 5 seconds
function repeatedPrint() {
setTimeout(function () {
// you have to provide a new start date to get updated information
countdownInfo = countdown(new Date(), future);
console.log(countdownInfo.toString());
repeatedPrint();
}, 5 * 1000);
}
repeatedPrint();

Exception Dates Array handling in Nodejs Cron

I'm using Cron; a nodejs package for cron job handling in NodeJs. Here's how I'm running a cron job:
var job = new CronJob({
cronTime: '00 30 11 * * 1-5',
onTick: function() {
/*
* Runs every weekday (Monday through Friday)
* at 11:30:00 AM. It does not run on Saturday
* or Sunday.
*/
}
});
job.start();
It's running flawlessly but is there any standard way to handle exception dates array handling? For example here's my dates array of national holidays and I don't want to run my cron job on these days:
['28-01-2017', '1-05-2017', '14-08-2016', '15-09-2016', '16-09-2016']
You can not add exclusions to your cron job. You are much better off adding to your code the logic to not run on those days.
var job = new CronJob({
cronTime: '00 30 11 * * 1-5',
onTick: function() {
var exclude = ['28-01-2017', '1-05-2017', '14-08-2016', '15-09-2016', '16-09-2016']
if (exclude.indexOf(convertDate()) > -1) {
console.log('dont run');
} else {
console.log('run');
}
}
});
job.start();
function convertDate() {
var d = new Date();
return [pad(d.getDate()), pad(d.getMonth()+1), d.getFullYear()].join('-');
}
function pad(s) {
return (s < 10) ? '0' + s : s;
}

Schedule task for every 4 hours in Node.js

How could I schedule a task to run after 4 hours using "node-schedule" in Node.js
Currently my code is as below but it isn't responding as expected.
var schedule = require('node-schedule');
var task = schedule.scheduleJob('* */4 * * *', function () {
console.log('Scheduled Task');
});
Your syntax creates a cron that runs every minute every 4 hours.
The syntax you are looking for is 0 */4 * * *. Wich executes ONCE every 4 hours.
You can test the cron syntax with the website http://crontab.guru
Another option setting your cron in node is using rules. See https://github.com/node-schedule/node-schedule
var cron = require('node-schedule');
var rule = new cron.RecurrenceRule();
rule.hour = 4;
rule.minute = 0;
cron.scheduleJob(rule, function(){
console.log(new Date(), 'Every 4 hours');
});
try this
var cron = require('node-schedule');
var rule = new cron.RecurrenceRule();
rule.hour = new cron.Range(0,23,4);
rule.minute = 0;
cron.scheduleJob(rule, function(){
console.log(new Date(), 'Every 4 hours');
});
new cron.Range(0,23,4); 4 is the optional step parameter

Resources