Switch to poolifier worker threads pool implementation.
[e-mobility-charging-stations-simulator.git] / src / charging-station / StationWorker.ts
1 import { WorkerData, WorkerEvents } from '../types/Worker';
2 import { isMainThread, parentPort, workerData } from 'worker_threads';
3
4 import ChargingStation from './ChargingStation';
5 import Constants from '../utils/Constants';
6 import { ThreadWorker } from 'poolifier';
7 import Utils from '../utils/Utils';
8
9 if (!isMainThread) {
10 // Add listener to start charging station from main thread
11 addListener();
12 if (!Utils.isUndefined(workerData)) {
13 startChargingStation({ index: workerData.index as number, templateFile: workerData.templateFile as string });
14 }
15 }
16
17 function addListener() {
18 parentPort.on('message', (message) => {
19 if (message.id === WorkerEvents.START_WORKER_ELEMENT) {
20 startChargingStation(message.workerData);
21 }
22 });
23 }
24
25 function startChargingStation(data: WorkerData) {
26 const station = new ChargingStation(data.index , data.templateFile);
27 station.start();
28 }
29
30 export default new ThreadWorker(startChargingStation, { maxInactiveTime: Constants.WORKER_POOL_MAX_INACTIVE_TIME, async: false });