Skip to content

Commit

Permalink
demonstrate async cleanup in graceful shutdowns
Browse files Browse the repository at this point in the history
  • Loading branch information
hunterloftis committed Sep 21, 2020
1 parent 83126e5 commit a771229
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 21 deletions.
6 changes: 4 additions & 2 deletions examples/complex.js
Expand Up @@ -19,10 +19,12 @@ function worker(id, disconnect) {
process.on('SIGTERM', shutdown)
process.on('SIGINT', shutdown)

function shutdown() {
async function shutdown() {
if (exited) return
exited = true
console.log(`Worker ${ id } cleanup.`)

await new Promise(r => setTimeout(r, 300)) // simulate async cleanup work
console.log(`Worker ${ id } cleanup done.`)
disconnect()
}
}
18 changes: 12 additions & 6 deletions readme.md
Expand Up @@ -103,12 +103,18 @@ function master() {

// This will be called four times
function worker(id, disconnect) {
let exited = false

console.log(`Started worker ${ id }`)
process.on('SIGTERM', shutdown)
process.on('SIGINT', shutdown)

function shutdown() {
console.log(`Worker ${ id } cleanup.`)
async function shutdown() {
if (exited) return
exited = true

await new Promise(r => setTimeout(r, 300)) // simulate async cleanup work
console.log(`Worker ${ id } cleanup done.`)
disconnect()
}
}
Expand All @@ -122,10 +128,10 @@ Started worker 3
Started worker 2
Started worker 4
^C
Worker 1 cleanup.
Worker 3 cleanup.
Worker 2 cleanup.
Worker 4 cleanup.
Worker 1 cleanup done.
Worker 3 cleanup done.
Worker 2 cleanup done.
Worker 4 cleanup done.
Master cleanup.
```

Expand Down
15 changes: 8 additions & 7 deletions test/fixtures/graceful-sigusr2.js
@@ -1,17 +1,18 @@
'use strict';

const throng = require('../../lib/throng');
const throng = require('../../lib/throng')

throng({
workers: 3,
signals: ['SIGUSR2'],
start: (id, disconnect) => {
console.log('worker');

process.on('SIGUSR2', exit);
let exited = false

console.log('worker')
process.on('SIGUSR2', exit)

function exit() {
console.log(`exiting`);
if (exited) return
exited = true
console.log(`exiting`)
disconnect()
}
}
Expand Down
11 changes: 5 additions & 6 deletions test/fixtures/graceful.js
@@ -1,19 +1,18 @@
'use strict';

const throng = require('../../lib/throng');
const throng = require('../../lib/throng')

throng(3, (id, disconnect) => {
let exited = false

console.log('worker');

console.log('worker')
process.on('SIGTERM', exit)
process.on('SIGINT', exit)

async function exit() {
if (exited) return
exited = true

await new Promise(r => setTimeout(r, 100)) // simulate async cleanup
console.log('exiting')
disconnect()
}
});
})

0 comments on commit a771229

Please sign in to comment.