Ghost/ghost/job-manager/test/jobs/graceful.js
Naz 4b18cbcbdb Added support for worker threads in scheduled jobs
no issue

- When jobs are performing CPU intensive tasks they block main process'
event loop. They also can cause memory leaks or unexpected crashes
effectively crashing the parent proccess. To address these issues jobs need to be performed off of main
process. Worker Threads (https://nodejs.org/dist/latest-v12.x/docs/api/worker_threads.html)
are the best candidate for such work.
- These changes introduce an integration on top of bree
(https://github.com/breejs/bree/) which allows to run recurring
jobs in worker thereads. It falls back to child process execution for
Node v10 running without `--experimental-worker` flag.
- bree was chosen not only because it gives a polyfill for older Node
versions. It has support for some of the future use-cases Ghost is looking to
implement, like scheduled jobs.
- This changeset also includes a complete example of job running on an
interval with a possibility for graceful shutdown
2020-11-19 17:59:36 +13:00

33 lines
733 B
JavaScript

/* eslint-disable no-console */
const setTimeoutPromise = require('util').promisify(setTimeout);
const threads = require('bthreads');
let shutdown = false;
if (!threads.isMainThread) {
threads.parentPort.on('message', (message) => {
console.log(`paret message received: ${message}`);
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
process.exit(0);
}
}
})();