Skip to content

Instantly share code, notes, and snippets.

@munkhorgil
Last active May 22, 2020 06:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save munkhorgil/00ed33a9f973b604848f504262369fe5 to your computer and use it in GitHub Desktop.
Save munkhorgil/00ed33a9f973b604848f504262369fe5 to your computer and use it in GitHub Desktop.
Wait cronjob to finish when node app received the SIGINT signal
/**
* Description: Wait until cron jobs finish when node app received the SIGINT signal
* scripts: "dev": "DEBUG=Goblin:* pm2 start --kill_timeout 300000 app.js"
* Author: Munkh-Orgil
* Date: 22/05/2020
*/
const express = require('express')
const events = require('events');
const http = require('http')
const debug = require('debug');
const schedule = require('node-schedule');
const debugGoblin = debug('Goblin:');
const emitter = new events.EventEmitter();
const app = express()
app.get('/test', async function (req, res) {
debugGoblin('Test running...');
await new Promise(function(resolve, reject) {
setTimeout(function() {
resolve();
}, 20000);
});
debugGoblin('Test done');
})
const server = http.createServer(app);
app.listen(1234, function () {
debugGoblin('Server listening on PORT:1234');
initJobs();
})
/**
* subscribedJobs scheme
* { id: 1, name: 'name', status: 'pending' | 'done' }
*/
let subscribedJobs = [];
let receivedKill = false;
const canceledJobs = [];
emitter.on('start', function (data) {
debugGoblin(`subscribed-> id: ${data.id} name: ${data.name}`);
subscribedJobs.push(data);
});
emitter.on('end', function (data) {
const { id, status } = data;
const idx = subscribedJobs.findIndex(job => job.id === id);
subscribedJobs[idx].status = status;
debugGoblin(`job: ${id} is done`);
});
function waitForMe() {
return new Promise(function(resolve, reject) {
setTimeout(function() {
debugGoblin('Done');
resolve();
}, 15000);
});
}
function generateId() {
return '_' + Math.random().toString(36).substr(2, 9);
};
function initJobs() {
// every 5 sec
const job1 = schedule.scheduleJob('job-5sec', '*/5 * * * * *', async () => {
if (receivedKill) {
return canceledJobs.push(new Date());
}
const id = generateId();
emitter.emit('start', { id, name: 'job-5sec', status: 'pending' });
await waitForMe();
emitter.emit('end', { id, status: 'done' });
});
}
function checkStatus() {
const job = subscribedJobs.find(job => job.status === 'pending');
if (job) {
return debugGoblin(`job: ${job.id} is not finished status: ${job.status}`);
}
debugGoblin('Goodbye cruel world');
debugGoblin(new Date(), canceledJobs);
process.exit(0);
}
process.on('SIGINT', function() {
receivedKill = true;
debugGoblin('Closing server...');
server.close(function() {
debugGoblin('Server closed...');
debugGoblin('Stopped receiving requests...');
});
setInterval(checkStatus, 2000);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment