Skip to content

panates/power-tasks

Repository files navigation

power-tasks

NPM Version NPM Downloads CI Tests Test Coverage

Powerful task management for JavaScript/TypeScript. Support for hierarchical tasks, dependencies, concurrency control, and a task queue.

Installation

  • npm install power-tasks --save

Node Compatibility

  • node >= 14.x

Core Concepts

Task

A Task represents a unit of work that can be executed. It can be a simple function, or it can have children and dependencies. Tasks are AsyncEventEmitter instances, meaning they emit events during their lifecycle.

Creating a Simple Task

import { Task } from 'power-tasks';

const task = new Task(async ({signal}) => {
  // Do some work
  return 'Result';
});

task.on('start', () => console.log('Task started!'));
task.on('finish', (t) => console.log(`Task finished with result: ${t.result}`));

await task.start();

Hierarchical Tasks

Tasks can have children. A parent task is considered finished when all its children are finished.

const parent = new Task([
  new Task(async () => 'Child 1'),
  new Task(async () => 'Child 2')
], {name: 'Parent Task'});

await parent.start();

Task Dependencies

Tasks can depend on other tasks by their name or instance. A task will wait for its dependencies to finish before starting.

const task1 = new Task(async () => 'Result 1', {name: 'T1'});
const task2 = new Task(async () => 'Result 2', {
  name: 'T2',
  dependencies: ['T1']
});

const parent = new Task([task1, task2]);
await parent.start();

TaskQueue

TaskQueue manages a list of tasks with concurrency control. It allows you to limit the number of tasks running at the same time and provides methods to pause, resume, and clear the queue.

import { TaskQueue } from 'power-tasks';

const queue = new TaskQueue({concurrency: 2});

queue.enqueue(async () => { /* ... */
});
queue.enqueue(async () => { /* ... */
});
queue.enqueue(async () => { /* ... */
});

await queue.wait(); // Wait for all tasks to finish

API Reference

Task

A Task represents a unit of work that can be executed. It supports hierarchical tasks, dependencies, and emits events throughout its lifecycle.

Constructor

  • new Task(execute, options?)
    • execute: TaskFunction - The function to be executed by the task.
    • options: `TaskOptions - Configuration options for the task.
  • new Task(children, options?)
    • children: TaskLike[] - An array of child tasks or task functions.
    • options: TaskOptions - Configuration options for the task.

Properties

Property Type Description
id string Unique identifier of the task.
name string | undefined Name of the task.
status TaskStatus Current status of the task.
message string Current message of the task.
result any Result produced by the task.
error any Error if the task failed.
isFailed boolean Whether the task has failed.
isAborted boolean Whether the task has been aborted or aborting
isFinished boolean Whether the task has completed (successfully, failed, or aborted).
isStarted boolean Whether the task has started but not yet finished.
executeDuration number | undefined Duration of the task execution in milliseconds.
children Task[] | undefined List of child tasks.
dependencies Task[] | undefined List of tasks this task depends on.
failedChildren Task[] | undefined List of child tasks that failed.
failedDependencies Task[] | undefined List of dependencies that failed.
needWaiting boolean Whether the task is currently waiting for children or dependencies to finish.
options TaskOptions Task configuration options.
parent Task | undefined The parent task if this is a child task.

Methods

  • start(): Starts the task execution. Returns the task instance.
    task.start();
  • abort(): Aborts the task execution. Returns the task instance.
    task.abort();
  • toPromise(): Returns a promise that resolves with the task result or rejects with the task error.
    const result = await task.toPromise();
  • getWaitingTasks(): Gets a list of tasks that this task is currently waiting for.
    const waitingTasks = task.getWaitingTasks();
  • reset(): Resets the task to its initial state so it can be started again.
    task.reset();
  • toJSON(): Returns a JSON-compatible representation of the task.
    const json = task.toJSON();

Events

  • start: Emitted when the task starts.
    task.on('start', (task) => console.log('Started'));
  • run: Emitted when the execution function is called.
    task.on('run', (task) => console.log('Running'));
  • finish: Emitted when the task finishes (successfully, failed, or aborted).
    task.on('finish', (task) => console.log('Finished'));
  • abort: Emitted when the task is aborted.
    task.on('abort', (task) => console.log('Aborted'));
  • status-change: Emitted when the task status changes.
    task.on('status-change', (task, status) => console.log('Status changed to', status));
  • update: Emitted when task properties are updated.
    task.on('update', (task, properties) => console.log('Updated', properties));
  • update-recursive: Emitted when properties of the task or any of its children are updated.
    task.on('update-recursive', (task, properties) => console.log('Recursive update', properties));
  • error: Emitted when an error occurs.
    task.on('error', (error, task) => console.error(error));
  • wait-end: Emitted when the task stops waiting for dependencies.
    task.on('wait-end', () => console.log('Wait ended'));

TaskOptions

Option Type Description
id any Unique identifier for the task.
name string Name of the task (used for dependencies).
args any[] Arguments passed to the task function.
children TaskLike[] | () => ... List of child tasks or a function that returns them.
dependencies (Task | string)[] Tasks that must finish before this task starts.
concurrency number Number of child tasks to run in parallel.
bail boolean If true (default), aborts children if one fails.
serial boolean If true, runs children one by one (shortcut for concurrency: 1).
exclusive boolean If true, the task queue waits for this task to complete exclusively.
abortSignal AbortSignal An optional AbortSignal object that can be used to communicate with, or to abort, an operation.
abortTimeout number Timeout in ms to wait for aborting tasks.
onStart Function Callback invoked when the task starts.
onFinish Function Callback invoked when the task finishes.
onRun Function Callback invoked when the task's execution function begins.
onStatusChange Function Callback invoked when the task's status changes.
onUpdate Function Callback invoked when the task's properties are updated.
onUpdateRecursive Function Callback invoked when properties of the task or its children are updated.

TaskStatus

A task can be in one of the following states:

  • idle: Task is created but not yet started.
  • waiting: Task is waiting for its dependencies.
  • running: Task is currently executing.
  • fulfilled: Task completed successfully.
  • failed: Task failed with an error.
  • aborting: Task is in the process of being aborted.
  • aborted: Task has been aborted.

TaskQueue

TaskQueue manages the execution of tasks with concurrency control.

Constructor

  • new TaskQueue(options?)
    • options: TaskQueueOptions - Configuration options for the queue.

Properties

Property Type Description
size number Total number of tasks in the queue (both queued and running).
running number Number of tasks currently running.
queued number Number of tasks currently waiting in the queue.
paused boolean Whether the queue is currently paused.
concurrency number | undefined The maximum number of tasks to run concurrently.
maxQueue number | undefined The maximum number of tasks allowed in the queue.

Methods

  • enqueue(task): Adds a task to the end of the queue. Returns the Task instance.
    const task = queue.enqueue(async () => 'Done');
  • enqueuePrepend(task): Adds a task to the beginning of the queue. Returns the Task instance.
    queue.enqueuePrepend(myTask);
  • getTask(id): Retrieves a task by its ID. Returns the Task instance if found, or undefined otherwise.
    const task = queue.getTask('my-task-id');
  • pause(): Pauses the queue execution.
    queue.pause();
  • resume(): Resumes the queue execution.
    queue.resume();
  • clearQueue(): Removes all queued tasks and aborts them.
    queue.clearQueue();
  • abortAll(): Aborts all running tasks and clears the queue.
    queue.abortAll();
  • wait(): Returns a promise that resolves when all tasks have finished and the queue is empty.
    await queue.wait();

Events

  • enqueue: Emitted when a task is added to the queue.
    queue.on('enqueue', (task) => console.log('Task enqueued'));
  • finish: Emitted when all tasks in the queue have finished and the queue is empty.
    queue.on('finish', () => console.log('Queue finished'));
  • error: Emitted when a task in the queue emits an error.
    queue.on('error', (error, task) => console.error(error));

TaskQueueOptions

Option Type Description
concurrency number The maximum number of tasks to run concurrently.
maxQueue number The maximum number of tasks allowed in the queue (including running).
paused boolean Whether the queue should start in a paused state.

License

MIT

About

Total task management

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors