- this.lastTaskTimestamp = Date.now()
- // Keep the worker active
- if (!isMain) {
- this.aliveInterval = setInterval(
- this.checkAlive.bind(this),
- (this.opts.maxInactiveTime ?? DEFAULT_MAX_INACTIVE_TIME) / 2
- )
- this.checkAlive.bind(this)()
- }
-
- this.mainWorker?.on('message', (value: MessageValue<Data, MainWorker>) => {
- this.messageListener(value, fn)
- })
- }
-
- protected messageListener (
- value: MessageValue<Data, MainWorker>,
- fn: (data: Data) => Response
- ): void {
- if (value.data !== undefined && value.id !== undefined) {
- // Here you will receive messages
- if (this.opts.async === true) {
- this.runInAsyncScope(this.runAsync.bind(this), this, fn, value)
- } else {
- this.runInAsyncScope(this.run.bind(this), this, fn, value)
- }
- } else if (value.parent !== undefined) {
- // Save a reference of the main worker to communicate with it
- // This will be received once
- this.mainWorker = value.parent
- } else if (value.kill !== undefined) {
- // Here is time to kill this worker, just clearing the interval
- if (this.aliveInterval != null) clearInterval(this.aliveInterval)
- this.emitDestroy()