74 lines
2.0 KiB
TypeScript
74 lines
2.0 KiB
TypeScript
|
import { NodeConnection } from "../helper/config";
|
||
|
import { uuid } from "../helper/mainHelper";
|
||
|
|
||
|
|
||
|
export class DataWorker {
|
||
|
|
||
|
/**
|
||
|
* An array of tasks that should be taken care of
|
||
|
*/
|
||
|
private nodeTasks : Array<NodeConnection> = [];
|
||
|
|
||
|
/**
|
||
|
* The amount of parallel tasks to run at once
|
||
|
*/
|
||
|
private parallelTasksCount: number;
|
||
|
|
||
|
private id: string;
|
||
|
|
||
|
/**
|
||
|
* @param parallelTasks The amount of parallel tasks that this Worker can run at once
|
||
|
*/
|
||
|
constructor(parallelTasks: number) {
|
||
|
// Initialize the amount of paralel tasks to run at the same time
|
||
|
this.parallelTasksCount = parallelTasks;
|
||
|
|
||
|
// Generate an ID for the worker
|
||
|
this.id = uuid();
|
||
|
}
|
||
|
|
||
|
public addNodeTask(node: NodeConnection) {
|
||
|
// Add the task to the list
|
||
|
this.nodeTasks.push(node);
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Start processing the node tasks.
|
||
|
*/
|
||
|
public async startProcessing() : Promise<void> {
|
||
|
|
||
|
// Go through all of the tasks to run
|
||
|
for ( let i = 0; i < this.nodeTasks.length; i++ ) {
|
||
|
// Spawn in the task queue
|
||
|
let taskQueue : Array<Promise<any>> = [];
|
||
|
|
||
|
// Start running the parallel tasks
|
||
|
for ( let x = 0; x < this.parallelTasksCount; x++ ) {
|
||
|
// Check if we have stept out of bounds
|
||
|
if ( i >= this.nodeTasks.length ) // Ignore out-of-bounds
|
||
|
break;
|
||
|
|
||
|
// Add the process to the queue
|
||
|
taskQueue.push(this.processTask(this.nodeTasks[i]))
|
||
|
// Add to the index
|
||
|
i += x;
|
||
|
}
|
||
|
|
||
|
// Get the results of the running
|
||
|
const runResults = await Promise.all(taskQueue);
|
||
|
|
||
|
console.log(runResults);
|
||
|
|
||
|
}
|
||
|
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Process a task
|
||
|
* @param task The task to process
|
||
|
*/
|
||
|
private async processTask(task: NodeConnection) {
|
||
|
return `[${this.id}]: Succesfully ran task ${task.name}`;
|
||
|
}
|
||
|
|
||
|
}
|