ScheduleWise
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/schedulewiseUsing Yarn
yarn add @kyo-services/schedulewiseUsing Pnpm
pnpm add @kyo-services/schedulewiseUsage
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
numberThe interval in milliseconds between task executions.
sw.scheduleTask(task, { interval: 5 * 60 * 1000 }); // Every 5 minutesname
stringOptional identifier for the task. Useful for finding and managing tasks later.
sw.scheduleTask(task, { name: 'dailyBackup' });immediate
booleanWhether to execute the task immediately upon creation.
sw.scheduleTask(task, { immediate: true });once
booleanIf true, the task will only execute once and then be removed.
sw.scheduleTask(task, { once: true, interval: 5000 }); // Run once after 5 secondsTask Methods
Methods available on task instances to control their behavior and state.
disable()
voidTemporarily 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 executingenable()
voidRe-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 executionupdate(options)
voidUpdates 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 secondsremove()
voidPermanently 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 removedTask Properties
Properties available on task instances to get information about their state and configuration.
id
numberUnique identifier for the task. Automatically assigned when the task is created.
const task = sw.scheduleTask(myFunction);
console.log(task.id); // e.g., 1name
string | undefinedOptional name identifier for the task. Useful for finding tasks later.
const task = sw.scheduleTask(myFunction, { name: 'backup' });
console.log(task.name); // 'backup'lastExecutionTime
DateTimestamp 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.000ZexecutionCount
numberNumber of times this task has been executed since creation.
const task = sw.scheduleTask(myFunction);
console.log(task.executionCount); // e.g., 5isEnabled
booleanCurrent enabled/disabled state of the task.
const task = sw.scheduleTask(myFunction);
console.log(task.isEnabled); // trueScheduler Methods
Global methods available on the scheduler instance to manage tasks and configurations.
scheduleTask(callback, options)
TaskCreates and schedules a new task with the specified callback and options.
Parameters:
callback: Function - The function to executeoptions: TaskOptions - Configuration options for the task
const task = sw.scheduleTask(
() => console.log('Task executed!'),
{ interval: 1000, immediate: true }
);once(callback, options)
TaskCreates a one-time task with a simplified API. The task will automatically be removed after execution.
Parameters:
callback: Function - The function to execute onceoptions: TaskOptions - Configuration options for the task
sw.once(
() => console.log('This is a one-time task'),
{ interval: 5000, name: 'simpleOneTimeTask' }
);pause()
voidPauses all task executions. Tasks will remain in the scheduler but won't execute until resumed.
sw.pause(); // All tasks are pausedresume()
voidResumes all task executions that were previously paused.
sw.resume(); // All tasks resume executionisPaused()
booleanChecks if the scheduler is currently paused.
const paused = sw.isPaused();
console.log('Scheduler is paused:', paused);findTask(identifier)
Task | undefinedFinds 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 IDremoveTask(identifier)
booleanRemoves 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 removedclearAllTasks()
voidRemoves all tasks from the scheduler.
sw.clearAllTasks(); // All tasks are removedgetAllTasks()
Task[]Returns an array of all scheduled tasks.
const tasks = sw.getAllTasks();
console.log(`Total tasks: ${tasks.length}`);changeProcessorInterval(newInterval)
voidChanges 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 500msBest 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 -- --coverageContributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes using conventional commits (
git commit -m 'feat: add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
License
This project is licensed under the MIT License - see the LICENSE file for details.