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.
Related
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();
}
}
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')
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()
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 am using agenda to run jobs in my nodejs application, below is my agenda.js file for agenda config.
var Agenda = require('agenda');
var connectionString = 'localhost:27017/csgo';
var agenda = new Agenda({db: { address: connectionString, collection: 'jobs' }});
require('./jobs/game_play')(agenda);
module.exports = agenda;
Below is my script to run a game play in every 5 seconds,
module.exports = function(agenda) {
agenda.define('start new play', function(job, done) {
console.log('new play agenda');
});
agenda.on('ready', function() {
agenda.every('5 seconds', 'start new play');
agenda.start();
});
}
After running my agenda.js script, below is my job which gets saved in the database,
{ "_id" : ObjectId("59423d0e4b9581f728af1b6a"), "name" : "start new play", "type" : "single", "data" : null, "priority" : 0, "repeatInterval" : "5 seconds", "repeatTimezone" : null, "lastModifiedBy" : null, "nextRunAt" : ISODate("2017-06-15T07:53:55.794Z"), "lockedAt" : ISODate("2017-06-15T07:53:50.789Z"), "lastRunAt" : ISODate("2017-06-15T07:53:50.794Z") }
Instead of 5 seconds,my job is running after every 5 minutes, what can be the problem.
add done() to finish the process. Hope it help!
module.exports = function(agenda) {
agenda.define('start new play', function(job, done) {
console.log('new play agenda');
done();
});
agenda.on('ready', function() {
agenda.every('5 seconds', 'start new play');
agenda.start();
});
}
Agenda module is based on human interval module(https://github.com/rschmukler/human-interval).
On the documentation you can see that seconds are supported but the min interval you can set is 1 minute.
They say that seconds are supported because you can set the interval as '1 minute and 30 seconds'.
You can try to pass interval as cron format:
module.exports = function(agenda) {
agenda.define('start new play', function(job, done) {
console.log('new play agenda');
});
agenda.on('ready', function() {
agenda.every('*/5 * * * * *', 'start new play');
agenda.start();
});
}
It it's not supported you would need to consider to use a different module like https://www.npmjs.com/package/node-cron or https://www.npmjs.com/package/node-schedule