X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Fcharging-station%2FChargingStationWorker.ts;h=741449e3b63e9b8126e4440c9c143116b61156b7;hb=178956d8c51c6a2b4ecc55b592dfb9ee339b8105;hp=19dd6f8dc2ed7960f5d7e9e3a29dcf6612ecf5e3;hpb=ca47912d4ef0ca7608be49e62aadb6a931d74359;p=e-mobility-charging-stations-simulator.git diff --git a/src/charging-station/ChargingStationWorker.ts b/src/charging-station/ChargingStationWorker.ts index 19dd6f8d..741449e3 100644 --- a/src/charging-station/ChargingStationWorker.ts +++ b/src/charging-station/ChargingStationWorker.ts @@ -1,7 +1,7 @@ // Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved. import { AsyncResource } from 'node:async_hooks'; -import { parentPort, workerData } from 'node:worker_threads'; +import { parentPort } from 'node:worker_threads'; import { ThreadWorker } from 'poolifier'; @@ -10,6 +10,8 @@ import type { ChargingStationWorkerData } from '../types'; import { Configuration } from '../utils'; import { WorkerConstants, type WorkerMessage, WorkerMessageEvents } from '../worker'; +const moduleName = 'ChargingStationWorker'; + /** * Create and start a charging station instance * @@ -19,6 +21,23 @@ const startChargingStation = (data: ChargingStationWorkerData): void => { new ChargingStation(data.index, data.templateFile).start(); }; +class ChargingStationWorker extends AsyncResource { + constructor() { + super(moduleName); + // Add message listener to create and start charging station from the main thread + parentPort?.on('message', (message: WorkerMessage) => { + if (message.id === WorkerMessageEvents.startWorkerElement) { + this.runInAsyncScope( + startChargingStation.bind(this) as (data: ChargingStationWorkerData) => void, + this, + message.data + ); + } + }); + } +} + +export let chargingStationWorker: ChargingStationWorker; // Conditionally export ThreadWorker instance for pool usage export let threadWorker: ThreadWorker; if (Configuration.workerPoolInUse()) { @@ -26,26 +45,5 @@ if (Configuration.workerPoolInUse()) { maxInactiveTime: WorkerConstants.POOL_MAX_INACTIVE_TIME, }); } else { - class ChargingStationWorker extends AsyncResource { - constructor() { - super('ChargingStationWorker'); - } - - public run(data: ChargingStationWorkerData): void { - this.runInAsyncScope( - startChargingStation.bind(this) as (data: ChargingStationWorkerData) => void, - this, - data - ); - } - } - // Add message listener to create and start charging station from the main thread - parentPort?.on('message', (message: WorkerMessage) => { - if (message.id === WorkerMessageEvents.startWorkerElement) { - new ChargingStationWorker().run(message.data); - } - }); - if (workerData !== undefined) { - new ChargingStationWorker().run(workerData as ChargingStationWorkerData); - } + chargingStationWorker = new ChargingStationWorker(); }