-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworker.js
More file actions
53 lines (40 loc) · 1.66 KB
/
worker.js
File metadata and controls
53 lines (40 loc) · 1.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
const { Worker, isMainThread, parentPort, workerData } = require('worker_threads');
const sleep = require('sleep-promise');
if (isMainThread) {
throw new Error('This file is a worker thread and should not be run directly.')
}
const port = parentPort
if (!port) throw new Error('IllegalState')
const workerid = workerData.id
const work = workerData.args
let workerID = 'worker-'+workerid
let workerState = 'running'
port.on('message', data => {
const { operation, worker, status, state } = data
if (operation === 'internal') {
if (status === 'ping') {
port.postMessage({ operation: 'log', worker: workerID, status: 'pong', state: 'ok' })
}
if (status === 'exit') {
workerState = 'exiting'
port.postMessage({ operation: 'internal', worker: workerID, status: 'exit-forced', state: 'ok' })
port.close()
}
}
})
const sleepTime = Math.floor(Math.random() * 10000) + 1000
port.postMessage({ operation: 'internal', worker: workerID, status: 'running', state: 'ok' })
port.postMessage({ operation: 'log', worker: workerID, status: 'Worker is now operational!', state: 'ok' })
sleep(sleepTime).then(() => {
if (workerState === 'running') {
//port.postMessage({ operation: 'log', worker: workerID, status: 'Idle...', state: 'ok' })
}
}).catch(err => {
port.postMessage({ operation: 'log', worker: workerID, status: err, state: 'error' })
port.postMessage({ operation: 'internal', worker: workerID, status: 'error', state: 'ok' })
port.close()
}).finally(() => {
//port.postMessage({ operation: 'log', worker: workerID, status: 'Exiting!', state: 'ok' })
port.postMessage({ operation: 'internal', worker: workerID, status: 'exit', state: 'ok' })
port.close()
})