JSPM

lightning-timer

2.0.0
    • ESM via JSPM
    • ES Module Entrypoint
    • Export Map
    • Keywords
    • License
    • Repository URL
    • TypeScript Types
    • README
    • Created
    • Published
    • Downloads 4
    • Score
      100M100P100Q23971F
    • License MIT

    High-performance in-memory timer library with nanosecond precision for handling large volumes of timers

    Package Exports

    • lightning-timer
    • lightning-timer/dist/index.js

    This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (lightning-timer) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

    Readme

    ⚡ Lightning Timer

    High-performance TypeScript library for managing large volumes of timers with nanosecond precision. Features a priority queue-based implementation with support for webhooks, Kafka messages, and custom function callbacks.

    Features

    • Nanosecond Precision: Uses Node.js high-resolution time for precise scheduling
    • Priority Queue: Efficient min-heap implementation for O(log n) operations
    • Game Loop Architecture: Configurable tick rate for processing timers
    • Dynamic Callbacks: Support for webhooks, Kafka messages, and custom functions
    • Concurrent Execution: Configurable max concurrent callback executions
    • Retry Logic: Built-in retry mechanism for failed callbacks
    • High Performance: Optimized for handling thousands of timers per second

    Installation

    npm install lightning-timer

    Quick Start

    import { LightningTimer } from 'lightning-timer';
    
    const timer = new LightningTimer({
      tickRate: 1,  // Check timers every 1ms
      maxConcurrentCallbacks: 100,
      enableLogging: true
    });
    
    // Schedule using UTC timestamp (milliseconds)
    const futureTime = Date.now() + 5000; // 5 seconds from now
    timer.scheduleFunctionAt(futureTime, () => {
      console.log('Timer executed!');
    });
    
    // Schedule using nanosecond timestamp (BigInt)
    const nanoTime = BigInt(Date.now()) * 1000000n + 100000000n; // 100ms from now in nanoseconds
    timer.scheduleFunctionAt(nanoTime, () => {
      console.log('Precise timer executed!');
    });
    
    // Or use convenience methods with delay in ms
    timer.scheduleFunction(100, () => {
      console.log('Timer after 100ms!');
    });
    
    // Schedule a webhook at specific time
    const webhookTime = new Date('2025-01-26T10:00:00Z').getTime();
    timer.scheduleWebhookAt(webhookTime, {
      url: 'https://api.example.com/webhook',
      method: 'POST',
      body: { message: 'Scheduled webhook' }
    });
    
    // Start the timer
    timer.start();

    API Reference

    LightningTimer

    const timer = new LightningTimer({
      tickRate?: number;              // Game loop tick rate in ms (default: 1)
      maxConcurrentCallbacks?: number; // Max concurrent executions (default: 100)
      enableLogging?: boolean;         // Enable debug logging (default: false)
    });

    Scheduling Methods

    Schedule at specific UTC timestamp:

    // Using millisecond timestamp (number)
    timer.scheduleAt(timestampMs: number, callback: TimerCallback, metadata?: any): string;
    timer.scheduleFunctionAt(timestampMs: number, fn: () => void | Promise<void>, metadata?: any): string;
    timer.scheduleWebhookAt(timestampMs: number, config: WebhookConfig, metadata?: any): string;
    timer.scheduleKafkaAt(timestampMs: number, config: KafkaConfig, metadata?: any): string;
    
    // Using nanosecond timestamp (bigint)
    const nanoTime = BigInt(Date.now()) * 1000000n;
    timer.scheduleAt(nanoTime, callback, metadata): string;

    Schedule with delay (convenience methods):

    // Schedule with delay in milliseconds from now
    timer.schedule(delayMs: number, callback: TimerCallback, metadata?: any): string;
    timer.scheduleFunction(delayMs: number, fn: () => void | Promise<void>, metadata?: any): string;
    timer.scheduleWebhook(delayMs: number, config: WebhookConfig, metadata?: any): string;
    timer.scheduleKafka(delayMs: number, config: KafkaConfig, metadata?: any): string;

    Kafka Configuration

    import { CallbackExecutor } from 'lightning-timer';
    
    const executor = new CallbackExecutor();
    await executor.configureKafka({
      clientId: 'timer-service',
      brokers: ['localhost:9092'],
      ssl: true,
      sasl: {
        mechanism: 'plain',
        username: 'user',
        password: 'pass'
      }
    });

    Examples

    Running Examples

    npm run example:basic    # Basic timer functionality
    npm run example:webhook  # Webhook integration example
    npm run example:stress   # Stress test with 10,000 timers

    Stress Test Performance

    The library can handle 10,000+ timers efficiently:

    // Schedule 10,000 timers at specific timestamps
    const baseTime = Date.now();
    for (let i = 0; i < 10000; i++) {
      const executeAt = baseTime + Math.random() * 1000;
      timer.scheduleFunctionAt(executeAt, () => {
        // Timer callback
      });
    }

    Architecture

    • Priority Queue: Min-heap for O(log n) insertion/extraction
    • Game Loop: Continuous processing at configured tick rate
    • Nanosecond Timing: Using process.hrtime.bigint() for precision
    • Batch Processing: Processes multiple ready timers per tick
    • Concurrent Limits: Prevents overwhelming system resources

    Performance Considerations

    • Tick rate affects precision vs CPU usage trade-off
    • Lower tick rates (1ms) provide better precision but higher CPU usage
    • Adjust maxConcurrentCallbacks based on your system resources
    • For Kafka callbacks, ensure producer is properly configured before use

    License

    MIT