Created
January 9, 2018 16:57
-
-
Save romeosierra1/76d42d086cfdc1b8c67dc527f09e8dff to your computer and use it in GitHub Desktop.
A Cron Script to schdule a task to perform SQL tasks.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const cron = require('node-cron'); | |
let fs = require('fs'); | |
let sql = require('mssql/msnodesqlv8'); | |
let mssql = require('mssql'); | |
let lastid = 0; | |
let config = { | |
driver: 'msnodesqlv8', | |
connectionString: 'Driver={SQL Server Native Client 10.0};Server=localhost\\Username;Database=Database;Trusted_Connection=yes;' | |
//This config is for making a connnection with SQL Server using Windows Authentication. | |
}; | |
var task = cron.schedule('1-59/10 * * * * *', () => { | |
if(fs.existsSync('cron.lock') === false) { | |
job(); | |
} else { | |
console.log('Another job is already running'); | |
} | |
}, false); | |
function job() { | |
fs.writeFileSync('cron.lock'); | |
let pool = new sql.ConnectionPool(config); | |
pool.connect(err => { | |
console.log(err); | |
let request = new sql.Request(pool); | |
request.input('lastid', mssql.Int, lastid) | |
.query('SELECT * FROM dbo.table WHERE ID > @lastid', (err, result) => { | |
console.log(err); | |
if (result.recordset.length > 0) { | |
console.log(result.recordset); | |
console.log(result.recordset[result.recordset.length - 1].ID); | |
lastid = result.recordset[result.recordset.length - 1].ID; | |
} | |
pool.close(); | |
fs.unlinkSync('cron.lock'); | |
}) | |
}); | |
} | |
task.start(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment