@webergency-utils/timer
v1.0.2
Published
An efficient and robust task scheduling and cron timer library for Node.js supporting custom timezones and retries.
Readme
@webergency-utils/timer
An efficient, accurate, and robust task scheduling and cron timer library for Node.js. It supports interval-based timers, absolute/relative deadlines, cron expressions, custom timezones, and configurable retry backoffs.
TL;DR
import Timer from '@webergency-utils/timer';
const timer = new Timer();
// 1. Cron-style scheduling: Run every hour at minute 0
timer.set('sync-task', '0 * * * *', ({ id }) => {
console.log(`Running background sync task: ${id}`);
});
// 2. Interval-style scheduling: Run in 5 seconds, and repeat every 10 seconds
timer.set('poll-task', 5000, ({ id }) => {
console.log(`Running poll task: ${id}`);
}, { interval: 10000 });Installation & Setup
Install the package via npm:
npm install @webergency-utils/timerThis package supports both ES Modules (ESM) and CommonJS (CJS) natively. No external peer dependencies or environment configurations are required.
Architecture & Internals
- Binary Min-Heap: The library uses a binary min-heap (
Heap) under the hood to store and order scheduled tasks efficiently by their nearest firing deadline. This ensures that inserting, updating, or deleting tasks scales efficiently, even with thousands of concurrent schedules. - Single Active Timeout: Instead of spawning multiple node timeouts, a single timer instance manages exactly one
setTimeoutfor the nearest upcoming task. When it fires, the queue is dispatched, next deadlines are calculated, and the next timeout is scheduled. - Timezone-Aware Cron: Cron expressions are calculated using modern
Intl.DateTimeFormatAPIs to properly adjust for timezone transitions, daylight saving time (DST) shifts, and UTC offsets. - Robust Retries: Task execution failures (including asynchronous rejections) can trigger automatic retry policies. Retries support constant or exponential backoff with random jitter to prevent thundering herd problems.
Glossary
Timer: The main controller class used to manage a scheduler instance and schedule tasks.TimerCallback: A callback function type triggered when a scheduled task is executed.TimerOptions: Configuration settings for individual tasks (e.g. interval, timezone, offset, retries).RetryOptions: Settings for task retries upon failure (attempts, backoff style, delay).
API Reference
Timer (Class)
The primary controller for managing tasks.
Constructor
new Timer( options?: TimerConstructorOptions )
new Timer( name?: string, options?: TimerConstructorOptions )| Parameter | Type | Description |
| :--- | :--- | :--- |
| name | string | Optional name to identify the timer instance. |
| options | TimerConstructorOptions | Default configuration applied to all tasks scheduled on this instance. |
Public Methods
set()
Schedules a new task or updates an existing task with the same id.
timer.set<Data = any>(
id : string,
deadline : Date | number | string,
callback : TimerCallback<Data>,
options? : TimerOptions<Data>
): void| Parameter | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| id | string | Required | A unique identifier for this task. |
| deadline | Date \| number \| string | Required | The task schedule. Can be a future Date, relative/absolute milliseconds, or a cron string (e.g., '*/5 * * * *'). |
| callback | TimerCallback | Required | The function to run when the task triggers. |
| options | TimerOptions | {} | Optional configuration parameters. |
TimerOptions properties:
offset(number): Optional offset in milliseconds applied to the deadline (e.g.-1000fires 1 second early).expires(Date | number): Absolute timestamp or Date when the task automatically expires and stops triggering.data(any): Custom user context data passed to the callback function.interval(number): Interval in milliseconds for repeating tasks (cannot be combined with cron schedules).retry(RetryOptions | null): Task-specific retry settings. Passnullto explicitly disable retries.timezone(string): Task-specific timezone for cron timers (e.g.'Europe/Paris').
Throws
Errorif a cron string deadline is provided alongside anintervaloption.Errorifexpiresis a relative duration less than the safety limit.
postpone()
Reschedules an existing task to a new deadline.
timer.postpone(
id : string,
deadline : Date | number,
options? : Omit<TimerOptions, 'data' | 'interval'>
): booleanReturns true if the task exists and was successfully postponed; otherwise false.
unset()
Cancels a scheduled task and removes it from the timer.
timer.unset( id: string ): booleanReturns true if the task existed and was removed; otherwise false.
clear()
Cancels and removes all scheduled tasks.
timer.clear(): voidpause()
Pauses task execution.
timer.pause( id?: string ): boolean | void- If an
idis provided, pauses the specific task. Returnstrueif the task was found and paused. - If no
idis provided, pauses all task executions for this timer instance.
resume()
Resumes task execution.
timer.resume( id?: string ): boolean | void- If an
idis provided, resumes the specific task. Returnstrueif the task was found and resumed. - If no
idis provided, resumes all task executions for this timer instance.
destroy()
Clears all scheduled tasks and cleans up the instance from global registries.
timer.destroy(): voidhas()
Checks if a task with the given ID is registered.
timer.has( id: string ): booleanids()
Returns an array of all registered task IDs.
timer.ids(): string[]id()
Utility method to generate a unique task ID string.
timer.id( prefix?: string ): stringStatic Methods
Timer.pause()
Globally pauses all Timer instances. No tasks on any instances will execute until globally resumed.
Timer.pause(): voidTimer.resume()
Globally resumes all paused Timer instances.
Timer.resume(): voidTimer.id()
Generates a unique ID string. Useful for generating IDs for task scheduling.
Timer.id( prefix?: string ): stringConfiguration Interfaces & Types
TimerConstructorOptions
type TimerConstructorOptions = {
timezone? : string
retry? : RetryOptions
}RetryOptions
type RetryOptions = {
attempts? : number
delay? : number
backoff? : 'constant' | 'exponential'
}TimerCallback
type TimerCallback<Data = any> = (
context : {
id : string
data : Data
}
) => anyMaintenance
This package is actively maintained.
Bug reports and pull requests are welcome. Security issues and critical regressions are prioritized. New features are considered when they align with the package's existing scope.
