ScheduleWise

License: MITTypeScriptnpm versionNode VersionBrowser Support

A smart and efficient task scheduler for managing periodic jobs with precision timing and intelligent scheduling in both browser and Node.js environments.

Features

๐Ÿ”’

Singleton Pattern

Ensures single scheduler instance across your application

๐Ÿ“

Type-Safe

Full TypeScript support with type definitions

โšก

Zero Dependencies

No external runtime dependencies

๐Ÿงช

Well Tested

Comprehensive test coverage

Installation

Using NPM

npm install @kyo-services/schedulewise

Using Yarn

yarn add @kyo-services/schedulewise

Using Pnpm

pnpm add @kyo-services/schedulewise

Usage

Basic Task Scheduling

import sw from '@kyo-services/schedulewise';

// Create a periodic task
const task = sw.scheduleTask(
  (currentTime: Date, executionCount: number) => {
    console.log(`Task executed at ${currentTime}, count: ${executionCount}`);
  },
  {
    interval: 1000, // Run every second
    name: 'logTask', // Optional task identifier
    immediate: true // Run immediately when created
  }
);

One-Time Task

sw.scheduleTask(
  () => {
    console.log('This task runs only once after 5 seconds');
  },
  {
    interval: 5000,
    once: true
  }
);

Task Management

// Find task by name or ID
const task = sw.findTask('logTask');

// Disable task
task?.disable();

// Enable task
task?.enable();

// Update task configuration
task?.update({
  interval: 2000,
  immediate: false
});

// Pause all tasks
sw.pause();

// Check if scheduler is paused
console.log('Scheduler paused:', sw.isPaused()); // true

// Resume all tasks
sw.resume();

// Adjust processor interval (default: 100ms)
sw.changeProcessorInterval(500); // Set to 500ms

// Create a one-time task with simplified API
sw.once(
  () => console.log('This is a one-time task'),
  {
    interval: 5000,
    name: 'simpleOneTimeTask'
  }
);

Task Management

// Find task by name or ID
const task = sw.findTask('logTask');

// Disable task
task?.disable();

// Enable task
task?.enable();

// Update task configuration
task?.update({
  interval: 2000,
  immediate: false
});

// Pause all tasks
sw.pause();

// Check if scheduler is paused
console.log('Scheduler paused:', sw.isPaused()); // true

// Resume all tasks
sw.resume();

// Adjust processor interval (default: 100ms)
sw.changeProcessorInterval(500); // Set to 500ms

// Create a one-time task with simplified API
sw.once(
  () => console.log('This is a one-time task'),
  {
    interval: 5000,
    name: 'simpleOneTimeTask'
  }
);

Task Options

Configure how your tasks behave with these options when creating or updating tasks.

interface TaskOptions {
  interval: number;    // Interval in milliseconds
  name?: string;      // Optional task identifier
  immediate?: boolean; // Run immediately when created
  once?: boolean;     // Run only once
}

interval

Type: number

The interval in milliseconds between task executions.

sw.scheduleTask(task, { interval: 5 * 60 * 1000 }); // Every 5 minutes

name

Type: string

Optional identifier for the task. Useful for finding and managing tasks later.

sw.scheduleTask(task, { name: 'dailyBackup' });

immediate

Type: boolean

Whether to execute the task immediately upon creation.

sw.scheduleTask(task, { immediate: true });

once

Type: boolean

If true, the task will only execute once and then be removed.

sw.scheduleTask(task, { once: true, interval: 5000 }); // Run once after 5 seconds

Task Methods

Methods available on task instances to control their behavior and state.

disable()

Returns: void

Temporarily disables the task from executing. The task will remain in the scheduler but won't execute until enabled.

const task = sw.scheduleTask(myFunction, { interval: 1000 });
task.disable(); // Task will stop executing

enable()

Returns: void

Re-enables a previously disabled task. The task will resume executing according to its schedule.

const task = sw.scheduleTask(myFunction, { interval: 1000 });
task.disable();
// ... later
task.enable(); // Task resumes execution

update(options)

Returns: void

Updates the task's configuration. Can modify interval, name, or other properties.

Parameters:
  • options: TaskOptions - New configuration options for the task
const task = sw.scheduleTask(myFunction, { interval: 1000 });
task.update({ 
  interval: 2000,
  immediate: true 
}); // Task now runs every 2 seconds

remove()

Returns: void

Permanently removes the task from the scheduler. The task cannot be re-enabled after removal.

const task = sw.scheduleTask(myFunction, { interval: 1000 });
task.remove(); // Task is permanently removed

Task Properties

Properties available on task instances to get information about their state and configuration.

id

Type: number

Unique identifier for the task. Automatically assigned when the task is created.

const task = sw.scheduleTask(myFunction);
console.log(task.id); // e.g., 1

name

Type: string | undefined

Optional name identifier for the task. Useful for finding tasks later.

const task = sw.scheduleTask(myFunction, { name: 'backup' });
console.log(task.name); // 'backup'

lastExecutionTime

Type: Date

Timestamp of the last time this task was executed. Undefined if never executed.

const task = sw.scheduleTask(myFunction);
console.log(task.lastExecutionTime); // e.g., 2024-03-15T10:30:00.000Z

executionCount

Type: number

Number of times this task has been executed since creation.

const task = sw.scheduleTask(myFunction);
console.log(task.executionCount); // e.g., 5

isEnabled

Type: boolean

Current enabled/disabled state of the task.

const task = sw.scheduleTask(myFunction);
console.log(task.isEnabled); // true

Scheduler Methods

Global methods available on the scheduler instance to manage tasks and configurations.

scheduleTask(callback, options)

Returns: Task

Creates and schedules a new task with the specified callback and options.

Parameters:
  • callback: Function - The function to execute
  • options: TaskOptions - Configuration options for the task
const task = sw.scheduleTask(
  () => console.log('Task executed!'),
  { interval: 1000, immediate: true }
);

once(callback, options)

Returns: Task

Creates a one-time task with a simplified API. The task will automatically be removed after execution.

Parameters:
  • callback: Function - The function to execute once
  • options: TaskOptions - Configuration options for the task
sw.once(
  () => console.log('This is a one-time task'),
  { interval: 5000, name: 'simpleOneTimeTask' }
);

pause()

Returns: void

Pauses all task executions. Tasks will remain in the scheduler but won't execute until resumed.

sw.pause(); // All tasks are paused

resume()

Returns: void

Resumes all task executions that were previously paused.

sw.resume(); // All tasks resume execution

isPaused()

Returns: boolean

Checks if the scheduler is currently paused.

const paused = sw.isPaused();
console.log('Scheduler is paused:', paused);

findTask(identifier)

Returns: Task | undefined

Finds a task by its name or ID. Returns undefined if not found.

Parameters:
  • identifier: string | number - Task name or ID to find
const task = sw.findTask('dailyBackup');
// or
const task = sw.findTask(5); // by ID

removeTask(identifier)

Returns: boolean

Removes a task by its name or ID. Returns true if task was found and removed.

Parameters:
  • identifier: string | number - Task name or ID to remove
const removed = sw.removeTask('dailyBackup');
console.log(removed); // true if task was found and removed

clearAllTasks()

Returns: void

Removes all tasks from the scheduler.

sw.clearAllTasks(); // All tasks are removed

getAllTasks()

Returns: Task[]

Returns an array of all scheduled tasks.

const tasks = sw.getAllTasks();
console.log(`Total tasks: ${tasks.length}`);

changeProcessorInterval(newInterval)

Returns: void

Changes the scheduler's processor interval. Default is 100ms.

Parameters:
  • newInterval: number - New interval in milliseconds for the scheduler processor
// Adjust processor interval (default: 100ms)
sw.changeProcessorInterval(500); // Set to 500ms

Best Practices

Task Naming

Use descriptive names for better task management

sw.scheduleTask(sendEmail, { 
  name: 'dailyNewsletterTask'
});

Error Handling

Always handle task errors

sw.scheduleTask(async () => {
  try {
    await riskyOperation();
  } catch (error) {
    console.error('Task failed:', error);
  }
}, {
  interval: 1000
});

Resource Cleanup

Remove tasks when no longer needed

// In component unmount or cleanup
task.remove();

// or for all tasks
sw.clearAllTasks();

Interval Selection

Choose appropriate intervals

// Good: Clear intention
const MINUTE = 60 * 1000;
sw.scheduleTask(task, {
  interval: 5 * MINUTE
});

// Avoid: Magic numbers
sw.scheduleTask(task, {
  interval: 300000
});

Type Safety

Leverage TypeScript types

import type { TaskCallback, TaskOptions } from '@kyo-services/schedulewise';

const callback: TaskCallback = (time: Date, count: number) => {
  // Type-safe callback
};

Testing

# Run tests
npm test

# Run tests with coverage
npm test -- --coverage

Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes using conventional commits (git commit -m 'feat: add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

License

This project is licensed under the MIT License - see the LICENSE file for details.