npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

cron-monitor-js

v1.0.0

Published

Monitor and diagnose cron task health — track execution status, detect failures, and alert on anomalies

Readme

cron-monitor-js

Monitor and diagnose cron task health — track execution status, detect failures, and alert on anomalies.

Lightweight cron job monitoring for Node.js, OpenClaw, and distributed task environments. Zero dependencies. MIT licensed.

Features

Task Registration — Track cron jobs with custom names and schedules
Execution Recording — Log success/failure with duration and error messages
Automatic Alerts — Detect failures, slow runs, overdue tasks, and high failure rates
Health Reports — Generate overall system health snapshots
Prometheus Metrics — Export metrics for integration with monitoring stacks
Log Management — Persistent JSONL logs with automatic cleanup
CLI Interface — Command-line tool for easy integration
Zero Dependencies — No external npm packages required

Installation

As CLI Tool

npm install -g cron-monitor-js
cron-monitor help

As Library

npm install cron-monitor-js

Quick Start

CLI Usage

Register a cron task

cron-monitor register backup --name "Daily Backup" --schedule "0 3 * * *"

Record execution

# Success
cron-monitor record backup success --duration 2500 --msg "Backup completed"

# Failure
cron-monitor record backup failed --msg "Connection timeout"

Check status

cron-monitor status backup
cron-monitor health
cron-monitor summary

Export metrics

cron-monitor metrics

Programmatic Usage

const { CronMonitor } = require('cron-monitor-js');

// Initialize
const monitor = new CronMonitor({
  logDir: './cron-logs',
  alertThreshold: 300000, // 5 minutes
});

// Register tasks
monitor.register('backup', {
  name: 'Daily Backup',
  schedule: '0 3 * * *',
});

monitor.register('health-check', {
  name: 'API Health Check',
  schedule: '*/5 * * * *',
});

// Record executions
const startTime = Date.now();

try {
  // ... run your cron job ...
  
  monitor.recordExecution('backup', {
    status: 'success',
    duration: Date.now() - startTime,
    message: 'Backup completed successfully',
  });
} catch (error) {
  monitor.recordExecution('backup', {
    status: 'failed',
    duration: Date.now() - startTime,
    error: error.message,
  });
}

// Get health status
const health = monitor.healthReport();
console.log(`Health: ${health.status} (${health.healthy}/${health.totalTasks} healthy)`);

// Export metrics
console.log(monitor.metricsPrometheus());

// Cleanup old logs
monitor.cleanup(7); // Keep 7 days

API Reference

CronMonitor

Constructor

new CronMonitor(options = {})

Options:

  • logDir (string) — Directory for storing logs. Default: ./cron-logs
  • alertThreshold (number) — Milliseconds before alerting on slow tasks. Default: 300000 (5 min)

Methods

register(taskId, config)

Register a cron task.

monitor.register('my-task', {
  name: 'My Task',
  schedule: '0 */4 * * *', // Cron schedule (for reference)
});

Returns: Task object with metadata


recordExecution(taskId, result)

Record a task execution.

monitor.recordExecution('my-task', {
  status: 'success', // or 'failed'
  duration: 1500,    // milliseconds
  message: 'Completed',
  error: null,       // error message if failed
});

Auto-creates task if not registered.


getStatus(taskId)

Get a task's current status.

const task = monitor.getStatus('my-task');
// Returns: { id, name, lastRun, runCount, failCount, avgDuration, ... }

getSummary()

Get a summary of all tasks.

const summary = monitor.getSummary();
// Returns: { totalTasks, tasks: [...], recentAlerts: [...] }

healthReport()

Generate a comprehensive health report.

const report = monitor.healthReport();
// Returns: { status, totalTasks, healthy, unhealthy, summary, alerts, timestamp }

metricsPrometheus()

Export metrics in Prometheus text format.

const metrics = monitor.metricsPrometheus();
// cron_task_runs_total{task_id="...",task_name="..."} ...
// cron_task_failures_total{...} ...
// cron_task_duration_seconds{...} ...

cleanup(maxDays = 7)

Remove logs older than N days.

const result = monitor.cleanup(7);
// Returns: { removed: number, cutoff: Date }

Alerts

The monitor automatically generates alerts for:

| Alert | Severity | Trigger | |-------|----------|---------| | FAILURE | HIGH | Task execution failed | | SLOW_EXECUTION | MEDIUM | Duration > alertThreshold | | OVERDUE | HIGH | No execution in 2 × alertThreshold | | HIGH_FAILURE_RATE | HIGH | > 20% failures in last 5+ runs |

Access alerts via:

monitor.alerts // All alerts
monitor.getSummary().recentAlerts // Last 10
monitor.healthReport().alerts // Full report

CLI Commands

cron-monitor register <id> [--name STR] [--schedule STR]
  Register a new cron task

cron-monitor record <id> <status> [--duration MS] [--msg STR]
  Record a task execution

cron-monitor status <id>
  Show status of a specific task

cron-monitor health
  Show overall health with recent alerts

cron-monitor summary
  Show all tasks in table format

cron-monitor metrics
  Export Prometheus-format metrics

cron-monitor cleanup [--days N]
  Remove logs older than N days

cron-monitor config
  Show current configuration

Configuration

Set custom config file location:

export CRON_MONITOR_CONFIG=/etc/cron-monitor.json
cron-monitor health

Config file format:

{
  "logDir": "./cron-logs",
  "alertThreshold": 300000
}

Integration Examples

With Systemd Timer

# Register task
cron-monitor register systemd-backup --name "Systemd Backup Timer"

# In your backup script
cron-monitor record systemd-backup success --duration $DURATION

With OpenClaw Crons

// In your cron script
const { CronMonitor } = require('cron-monitor-js');
const monitor = new CronMonitor();

monitor.register('openclaw-cron-1', { name: 'Auto-Dev Sync' });

try {
  // Your cron logic here
  monitor.recordExecution('openclaw-cron-1', {
    status: 'success',
    duration: elapsed,
  });
} catch (e) {
  monitor.recordExecution('openclaw-cron-1', {
    status: 'failed',
    error: e.message,
  });
}

Prometheus Scraping

# Expose metrics via simple HTTP server
node -e "
const { CronMonitor } = require('cron-monitor-js');
const http = require('http');
const monitor = new CronMonitor();

http.createServer((req, res) => {
  if (req.url === '/metrics') {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end(monitor.metricsPrometheus());
  }
}).listen(9090);
"

Testing

Run the included test suite:

npm test

All 15 tests should pass:

  • Task registration
  • Execution recording
  • Auto-registration
  • Duration calculation
  • Failure detection
  • Alert generation
  • Log persistence
  • Summary generation
  • Health reporting
  • Metrics export
  • Cleanup
  • And more...

Requirements

  • Node.js 14+
  • No external dependencies

License

MIT

Author

OpenClaw Contributors


Zero dependencies. MIT licensed. Production-ready.

Perfect for monitoring distributed cron tasks, OpenClaw automation, and homelab job execution.