Files
taskbuffer/ts/taskbuffer.classes.taskrunner.ts

70 lines
1.7 KiB
TypeScript
Raw Normal View History

2022-03-25 12:14:49 +01:00
import * as plugins from './taskbuffer.plugins.js';
2019-11-27 23:34:45 +00:00
2022-03-25 12:14:49 +01:00
import { Task } from './taskbuffer.classes.task.js';
import { logger } from './taskbuffer.logging.js';
2019-11-27 23:34:45 +00:00
export class TaskRunner {
public maxParallelJobs: number = 1;
2019-11-27 23:34:45 +00:00
public status: 'stopped' | 'running' = 'stopped';
public runningTasks: plugins.lik.ObjectMap<Task> =
new plugins.lik.ObjectMap<Task>();
public queuedTasks: Task[] = [];
2019-11-27 23:34:45 +00:00
constructor() {
2020-07-12 00:48:51 +00:00
this.runningTasks.eventSubject.subscribe(async (eventArg) => {
this.checkExecution();
});
}
2019-11-27 23:34:45 +00:00
/**
* adds a task to the queue
2019-11-27 23:34:45 +00:00
*/
public addTask(taskArg: Task) {
this.queuedTasks.push(taskArg);
this.checkExecution();
2019-11-27 23:34:45 +00:00
}
/**
* set amount of parallel tasks
* be careful, you might lose dependability of tasks
2019-11-27 23:34:45 +00:00
*/
public setMaxParallelJobs(maxParallelJobsArg: number) {
this.maxParallelJobs = maxParallelJobsArg;
2019-11-27 23:34:45 +00:00
}
/**
* starts the task queue
*/
2019-11-28 14:42:28 +00:00
public async start() {
2019-11-27 23:34:45 +00:00
this.status = 'running';
}
/**
* checks whether execution is on point
*/
2019-11-27 23:34:45 +00:00
public async checkExecution() {
if (
this.runningTasks.getArray().length < this.maxParallelJobs &&
this.status === 'running' &&
this.queuedTasks.length > 0
) {
const nextJob = this.queuedTasks.shift();
2019-11-27 23:34:45 +00:00
this.runningTasks.add(nextJob);
try {
await nextJob.trigger();
} catch (err) {
logger.log('error', `TaskRunner: task "${nextJob.name || 'unnamed'}" failed: ${err instanceof Error ? err.message : String(err)}`);
}
this.runningTasks.remove(nextJob);
this.checkExecution();
2019-11-27 23:34:45 +00:00
}
}
/**
* stops the task queue
*/
2019-11-28 14:42:28 +00:00
public async stop() {
2019-11-27 23:34:45 +00:00
this.status = 'stopped';
}
2019-11-27 23:34:45 +00:00
}