Monday 5 June 2017

NodeJS set cron job to check MySQL database

I am new to NodeJS and setting cron jobs. Right now need to set a job using nodejs that will every 1min check MySql database for specific queries.

I tried with 'node-cron':

var cron = require('node-cron');
var mysql = require('mysql');

var con = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "",
  database: "test"
});

cron.schedule('* * * * *', function(){
  console.log('running a task 1min');

  con.connect(function(err) {
    if (err) throw err;
    console.log("Connected!");
     con.query("SELECT * from table", function (err, result) {
     if (err) throw err;
     console.log("Result: " + result);

     });

  });

});

Is that the proper way to create connection / end connection every time?

thanks.



via Joe

No comments:

Post a Comment