mirror of
https://gitlab.com/jusax23/dnc.git
synced 2024-11-22 06:36:40 +01:00
80 lines
1.8 KiB
JavaScript
80 lines
1.8 KiB
JavaScript
|
|
async function exitHandler(options, exitCode) {
|
|
shutdown().then(()=>{
|
|
setTimeout(function() {
|
|
process.exit();
|
|
}, 1000);
|
|
}).catch(()=>{
|
|
setTimeout(function() {
|
|
process.exit();
|
|
}, 10000);
|
|
});
|
|
}
|
|
[`SIGINT`, `SIGUSR1`, `SIGUSR2`,`SIGTERM`].forEach((eventType) => {
|
|
process.on(eventType, exitHandler.bind(null, eventType));
|
|
});
|
|
|
|
var shutdownTasks = []
|
|
|
|
export const addShutdownTask = function(task,maxDuration=5000){
|
|
shutdownTasks.push({t:task,d:maxDuration});
|
|
};
|
|
|
|
export const shutdown = function(){
|
|
return new Promise((res,rej)=>{
|
|
console.log("Shuting down ...");
|
|
|
|
var maxDuration = 1000;
|
|
var running = 0;
|
|
var timeout = null;
|
|
|
|
function mayShutdown(force=false){
|
|
if(running==0||force){
|
|
if(timeout!=null)clearInterval(timeout);
|
|
res();
|
|
}
|
|
}
|
|
running++;
|
|
for (var i = 0; i < shutdownTasks.length; i++) {
|
|
try {
|
|
if(shutdownTasks[i].d>maxDuration)maxDuration=shutdownTasks[i].d;
|
|
running++;
|
|
let a = shutdownTasks[i].t();
|
|
if(typeof a.then == "function"){
|
|
a.then(()=>{
|
|
running--;
|
|
mayShutdown();
|
|
}).catch(()=>{
|
|
running--;
|
|
mayShutdown();
|
|
});
|
|
}else{
|
|
running--;
|
|
if(shutdownTasks.length-1 == i){
|
|
mayShutdown();
|
|
}
|
|
}
|
|
} catch (e) {
|
|
running--;
|
|
mayShutdown();
|
|
}
|
|
}
|
|
running--;
|
|
timeout = setTimeout(function () {
|
|
timeout = null;
|
|
mayShutdown(true);
|
|
}, maxDuration);
|
|
mayShutdown();
|
|
});
|
|
};
|
|
export const saveShutdown = function(){
|
|
shutdown().then(() => {
|
|
setTimeout(function() { //some save time
|
|
process.exit();
|
|
}, 1000);
|
|
}).catch(() => {
|
|
setTimeout(function() { //shutdown on error with more save time
|
|
process.exit();
|
|
}, 10000);
|
|
});
|
|
}
|