How to run task in every 5 seconds with agenda in nodejs - node.js

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

Related

How to send email after a one week in nodejs

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()

Device shadow state not changes

Trying to create aws-iot device by using manual. I did all required settings while creating Pi3-DHT11-Node device. Simplified code below:
var awsIot = require('aws-iot-device-sdk');
const NODE_ID = 'Pi3-DHT11-Noded';
const INIT_DELAY = 15;
const TAG = '[' + NODE_ID + '] >>>>>>>>> ';
var thingShadow = awsIot.thingShadow({
keyPath: './certs_p/fea2f8efae7-private.pem.key',
certPath: './certs_p/fea2f8efae7-certificate.pem.crt',
caPath: './certs_p/AmazonRootCA1.pem',
clientId: NODE_ID,
host: 'a3cnel9blokzm0-ats.iot.eu-west-3.amazonaws.com',
port: 8883,
region: 'eu-west-3',
debug: true, // optional to see logs on console
});
thingShadow.on('connect', function() {
console.log(TAG, 'Connected.');
thingShadow.register(NODE_ID, {}, function() {
console.log(TAG, 'Registered.');
console.log(TAG, 'Reading data in ' + INIT_DELAY + ' seconds.');
setTimeout(sendData, INIT_DELAY * 1000); // wait for `INIT_DELAY` seconds before reading the first record
});
});
function sendData() {
var DHT11State = {
"state": {
"desired":
{
"temp": 20,
"humd": 33
}
}
};
var clientTokenUpdate = thingShadow.update(NODE_ID, DHT11State);
if (clientTokenUpdate === null) {
console.log(TAG, 'Shadow update failed, operation still in progress');
} else {
console.log(TAG, 'Shadow update success.');
}
// keep sending the data every 30 seconds
console.log(TAG, 'Reading data again in 30 seconds.');
setTimeout(sendData, 30000); // 30,000 ms => 30 seconds
}
Script is working fine, but this does not change shadow state. Why? How to fix that?
It is most likely that you do not have the device setup to sync the shadow to the cloud.
Follow the steps in this part of the tutorial, and ensure that you click on "Sync to the Cloud" as per Step 2, then redeploy your Greengrass Group.
https://docs.aws.amazon.com/greengrass/latest/developerguide/comms-enabled.html

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.

nodeJS agenda start job on a specific date

Is there any way to start a job on a specific date using the agenda library?
This is how I'm creating the jobs:
const someData = {
name: 'Name',
value: 'Value'
}
const job = await agenda.create('daily alert', someData);
await job.repeatEvery('1 day').save() // specify when to start
But at this moment the job starts right after it was created, and I want to somehow specify the date when it should start, like tomorrow.
Use agenda.schedule(when, job, data)
Schedules a job to run name once at a given time. when can be a Date
or a String such as tomorrow at 5pm.
https://github.com/agenda/agenda#schedulewhen-name-data-cb
agenda.define('send email report', {priority: 'high', concurrency: 10}, (job, done) => {
const {to} = job.attrs.data;
emailClient.send({
to,
from: 'example#example.com',
subject: 'Email Report',
body: '...'
}, done);
});
(async function() {
await agenda.start();
await agenda.schedule('tomorrow at 5pm', 'send email report', {to: 'admin#example.com'});
})();
This will work for you.
const scheduleAJobOnlyOnce = (options) => {
let job = this.Agenda.create(options.jobName, options);
job.schedule(options.start); // run at this time
job.save();
};
Define a "job", an arbitrary function that agenda can execute
const dt = new Date();
dt.setMinutes(dt.getMinutes()+60); // run after an hour
agenda.schedule(dt, 'hello'); // this will do it
agenda.start();

Multiple database connection in single connection pool using Node JS

I am trying to create a database connection pool in Node js using generic-pool package. With single database the pool is working fine but I want to use more than one database in single pool to be use. In this context I am facing issue. Generic pool is not creating pool for both the database in single pool. Below is my code. I am using trireme-jdbc for JDBC connection ang generic-pool for connection pooling.
var Pool = require('C:JCI/trireme-jdbc/node_modules/generic-pool').Pool;
var jdbc = require('C:/Program Files/nodejs/node_modules/trireme-jdbc');
var configOpenedge = require('C:/Program Files/nodejs/node_modules/trireme-jdbc/testconf/config-openedge.js');
var configPostgre = require('C:/Program Files/nodejs/node_modules/trireme-jdbc/testconf/config-postgre.js');
var pool = new Pool({
name : 'Anil-JCI',
create : function(callback) {
var connOpenedge = new jdbc.Database({
url : configOpenedge.url,
properties : configOpenedge.properties,
});
var connPostgre = new jdbc.Database({
url : configPostgre.url,
properties : configPostgre.properties,
/*
* minConnections : 1, maxConnections : 2000, idleTimeout : 60
*/
});
callback(null, connOpenedge);
},
destroy : function(client) {
client.end();
},
max : 10,
// optional. if you set this, make sure to drain() (see step 3)
min : 2,
// specifies how long a resource can stay idle in pool before being removed
idleTimeoutMillis : 30,
// if true, logs via console.log - can also be a function
log : true
});
console.log("connection created");
pool.acquire(function(err, clientOpenedge, clientPostgre) {
if (err) {
throw err;
}
else {
clientOpenedge.execute(
'select * from "po" where "po-num" = ? and "vend-num" = ? ', [
4322452, 4301170 ], function(err, result, rows) {
// pool.release(client);
console.log(err);
rows.forEach(function(row) {
console.log(row);
});
console.log("Openedge Data Printed...");
});
clientPostgre.execute("select * from employees ",
[ ], function(err, result) {
// pool.release(client);
console.log("we are in postgre");
console.log(result);
console.log("Postgre Data Printed...");
});
}
});

Resources