cron-monitor-js
v1.0.0
Published
Monitor and diagnose cron task health — track execution status, detect failures, and alert on anomalies
Maintainers
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 helpAs Library
npm install cron-monitor-jsQuick 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 summaryExport metrics
cron-monitor metricsProgrammatic 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 daysAPI Reference
CronMonitor
Constructor
new CronMonitor(options = {})Options:
logDir(string) — Directory for storing logs. Default:./cron-logsalertThreshold(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 reportCLI 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 configurationConfiguration
Set custom config file location:
export CRON_MONITOR_CONFIG=/etc/cron-monitor.json
cron-monitor healthConfig 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 $DURATIONWith 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 testAll 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.
