2020-11-19 07:58:41 +03:00
|
|
|
/* eslint-disable no-console */
|
|
|
|
|
|
|
|
const setTimeoutPromise = require('util').promisify(setTimeout);
|
2022-08-08 23:06:36 +03:00
|
|
|
const {isMainThread, parentPort} = require('worker_threads');
|
2020-11-19 07:58:41 +03:00
|
|
|
|
|
|
|
let shutdown = false;
|
|
|
|
|
2020-11-25 03:55:34 +03:00
|
|
|
if (!isMainThread) {
|
|
|
|
parentPort.on('message', (message) => {
|
2021-02-22 08:54:23 +03:00
|
|
|
console.log(`parent message received: ${message}`);
|
2020-11-25 03:56:01 +03:00
|
|
|
|
|
|
|
// 'cancel' event is triggered when job has to to terminated before it finishes execution
|
|
|
|
// usually it would come in when SIGINT signal is sent to a parent process
|
2020-11-19 07:58:41 +03:00
|
|
|
if (message === 'cancel') {
|
|
|
|
shutdown = true;
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
(async () => {
|
|
|
|
console.log('started graceful job');
|
|
|
|
|
|
|
|
for (;;) {
|
|
|
|
await setTimeoutPromise(1000);
|
|
|
|
console.log('worked for 1000 ms');
|
|
|
|
|
|
|
|
if (shutdown) {
|
|
|
|
console.log('exiting gracefully');
|
|
|
|
|
|
|
|
await setTimeoutPromise(100); // async cleanup imitation
|
|
|
|
|
2020-11-25 03:55:34 +03:00
|
|
|
if (parentPort) {
|
2020-11-30 03:48:07 +03:00
|
|
|
// `done' is a preferred method of shutting down the worker
|
2020-11-25 03:55:34 +03:00
|
|
|
// it signals job manager about finished job and the thread
|
|
|
|
// is later terminated through `terminate()` method allowing
|
|
|
|
// for unfinished pipes to flush (e.g. loggers)
|
2020-11-30 03:48:07 +03:00
|
|
|
//
|
|
|
|
// 'cancelled' is an allternative method to signal job was terminated
|
|
|
|
// because of parent initiated reason (e.g.: parent process interuption)
|
|
|
|
// differs from 'done' by producing different
|
2021-02-22 09:10:55 +03:00
|
|
|
// logging - shows the job was cancelled instead of completing
|
2020-11-25 03:55:34 +03:00
|
|
|
parentPort.postMessage('done');
|
2020-11-30 03:48:07 +03:00
|
|
|
// parentPort.postMessage('cancelled');
|
2020-11-25 03:55:34 +03:00
|
|
|
} else {
|
|
|
|
process.exit(0);
|
|
|
|
}
|
2020-11-19 07:58:41 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
})();
|