Runs a list of tasks one with the configured concurrency. When maxConcurrentTask is set to 1 this class behaves like a task queue. You can obtain info about tasks by listening to the events exposed by this class. See the events property for more information.

Example

In this example we simulate fetching 30 different people from an API. We simulated random fetching time that, by running the example, will result in out-of-order fetching.

const log = LoggerManager.getLogger("examples.task-runner-simple");

let personGenerated = 0;
const genPerson = (): Person => {
const personNo = ++personGenerated;
return {
name: `John ${personNo}`,
surname: `Doe ${personNo}`,
email: `jdoe${personNo}@mailinator.com`,
username: `john${personNo}`
};
};

const tr = new TaskRunner();
tr.events.taskCompleted.addListener(() => log.debug(`${people.length} people fetched so far`));
tr.waitForCompletion().then(() => log.debug("Execution complete"));

const people: Person[] = [];
for (let i = 0; i < 30; i++) {
tr.submitTask(async () => {
await delay(Math.round(Math.random() * 10));
const p = genPerson();
people.push(p);
});
}

Constructors

  • Constructs a new TaskRunner.

    Parameters

    • opts: TaskRunnerOptions = {}

      The following options can be provided: maxConcurrentTask: Max number of task executed concurrently. Extra tasks will be queued and executed when there will be room available.

    Returns default

Properties

_activeTasks: number = 0
_lastWorkerId: number = 0
events: {
    allTasksCompleted: default<void>;
    taskCompleted: default<default>;
    taskError: default<[default, any]>;
} = ...

We group event sources into this sub-object to make the code more readable.

Type declaration

  • allTasksCompleted: default<void>

    Emits an event any time the TaskRunner completes all pending tasks and has nothing left to do.

  • taskCompleted: default<default>

    Emits an event any time a task is completed. The only argument given is the completed task itself.

  • taskError: default<[default, any]>

    Emits an event any time a task throws an error. The first argument given is the task itself while the second the thrown error.

opts: Required<TaskRunnerOptions>

Options passed to the constructor after applying default values.

taskQueue: default[] = []

Pending tasks.

Methods

  • Returns true if no task is running and nothing is available in the queue.

    Returns boolean

  • Adds a new task to the runner that will be executed as soon as possible.

    Parameters

    • task: default | default<any>

      An object implementing the task interface or a function providing only the logic to execute. If using the latter one than a SimpleTask object is created.

    Returns void

  • Convenience method to wait for the next allTasksCompleted event

    Returns Promise<void>

Generated using TypeDoc