# Node.js Cron Monitoring: Detect Task Failures Early

> Monitor Node.js cron jobs, scheduled tasks, and background workers. Detect missed runs, silent failures, and queue backpressure in node-cron and Bull.

Source: https://crontinel.com/blog/nodejs-cron-monitoring/

Node.js powers everything from API servers to real-time data pipelines. But unlike PHP frameworks with built-in schedulers, Node.js teams rely on a mix of libraries — node-cron, node-schedule, Bull/BullMQ, Agenda, or custom setTimeout/setInterval logic. Each has different failure modes, and most teams don't discover problems until a customer reports missing data.

This guide covers how to monitor Node.js scheduled tasks across every common setup, what to watch for beyond "did it run," and how to catch failures before they become customer-facing issues.

> **Supported check-in today:** `fetch` the same HTTP outcome JSON as curl. Do not treat `npm i @crontinel/node` as parity with the Laravel package. Recipes: [docs.crontinel.com/check-in/recipes/](https://docs.crontinel.com/check-in/recipes/).

## The Node.js Scheduling Landscape

| Tool | Typical Use | Scheduling Model |
|------|-------------|-----------------|
| **node-cron** | Simple cron syntax | Cron expressions |
| **node-schedule** | Complex scheduling | Cron, interval, date |
| **Bull / BullMQ** | Distributed job queues | Redis-backed, repeatable jobs |
| **Agenda** | MongoDB-backed scheduling | Cron expressions, MongoDB persistence |
| **Bull Board** | Job queue monitoring | Dashboard for Bull queues |
| **Custom (setTimeout/setInterval)** | In-process timers | JavaScript timers |
| **PM2 / systemd** | Process management | Restart policies, health checks |

Each has different failure modes. A node-cron job that silently fails produces no output. A Bull queue that loses its Redis connection stops processing jobs without any error. An Agenda job stuck in a locked state never runs again.

## What to Monitor

### 1. Heartbeat — Did It Run?

The foundation. Your task sends a signal when it starts or finishes. If the signal doesn't arrive within the expected window, something is wrong.

**Without monitoring:** A Bull repeatable job stops running at 2am. You discover it at 9am when the daily report doesn't arrive.

**With monitoring:** Alert fires at 2:05am. You fix it before anyone notices.

```javascript
const cron = require('node-cron');

const ORIGIN = 'https://app.crontinel.com/api/v1/ingest';

async function send(path, body) {
  try {
    await fetch(`${ORIGIN}/${path}`, {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${process.env.CRONTINEL_INGEST_KEY}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(body),
      signal: AbortSignal.timeout(5000),
    });
  } catch {
    // Monitoring must not fail the business job.
  }
}

// Wrap any job: a running receipt, then completed or failed with the same key.
async function monitored(command, job) {
  const startedAt = new Date().toISOString();
  const request_key = `${command}-${startedAt}`;
  await send('cron', { command, request_key, status: 'running', started_at: startedAt });
  try {
    const records = await job();
    await send('cron', {
      command, request_key, status: 'completed', exit_code: 0,
      started_at: startedAt, finished_at: new Date().toISOString(),
      ...(typeof records === 'number' && { outcomes: { metrics: { processed_records: records } } }),
    });
    return records;
  } catch (error) {
    await send('cron', {
      command, request_key, status: 'failed', exit_code: 1,
      started_at: startedAt, finished_at: new Date().toISOString(), output: error.message,
    });
    throw error;
  }
}

cron.schedule('0 2 * * *', () => monitored('daily-report', generateReport));
```

The `running` receipt is what lets Crontinel alert when a job starts and never finishes. Register the job with its cron expression ([docs](https://docs.crontinel.com/check-in/schedule/)) and a run that never starts alerts too.

### 2. Duration — Is It Slow?

A job that usually takes 30 seconds suddenly takes 10 minutes. It still "works," but something is wrong — database lock, API rate limit, memory pressure.

**Watch for:**
- Jobs taking 2x+ longer than their historical average
- Gradual duration increase over days (memory leak)
- Spike in duration correlating with traffic or data volume

```javascript
// Duration comes from started_at and finished_at on the receipt.
await monitored('process-data', processData);
```

### 3. Exit Code — Did It Succeed?

A job runs, finishes, but throws an error. In node-cron, uncaught exceptions crash the process. In Bull, failed jobs go to a failed set. In custom schedulers, errors might be silently swallowed.

```javascript
// Bad: exception is caught and forgotten
try {
  await processQueue();
} catch (error) {
  console.error('Failed:', error); // Logged, but who's watching?
}

// Good: the wrapper sends a failed receipt, then rethrows
await monitored('process-queue', processQueue);
```

### 4. Queue Depth — Is Work Backing Up?

If your scheduled tasks push jobs to a queue (Redis, RabbitMQ), monitor the queue depth. A growing queue means workers can't keep up.

```javascript
const Bull = require('bull');

const queue = new Bull('email-notifications');

async function checkQueueDepth() {
  const counts = await queue.getJobCounts('waiting', 'active', 'completed', 'failed');
  
  if (counts.waiting > 1000) {
    await send('event', {
      type: 'queue.backlog',
      severity: 'warning',
      payload: { queue: 'email-notifications', ...counts },
    });
  }
  
  return counts;
}
```

### 5. Schedule Drift — Is It Running on Time?

A task scheduled for 2:00am starts running at 2:15am because the previous run took too long. Or timezone changes cause jobs to fire at the wrong time.

Register the job with its cron expression and a grace period. Crontinel alerts when the start does not arrive inside the window, so the job does not have to measure its own drift.

```bash
curl -sS -X POST "https://app.crontinel.com/api/v1/ingest/schedule" \
  -H "Authorization: Bearer $CRONTINEL_INGEST_KEY" \
  -H "Content-Type: application/json" \
  -d '{"source":"named_by_user","tasks":[{"command":"daily-sync","expression":"0 2 * * *","timezone":"UTC","grace_seconds":300}]}'
```

## Monitoring node-cron

node-cron is the most common choice for simple scheduling. It runs in-process, so if your application crashes, all scheduled jobs stop silently.

### Setup

```javascript
// Uses send() and monitored() from the first example.
cron.schedule('*/5 * * * *', () => monitored('health-check', checkServices).catch(() => {}));
```

### Common Failures

1. **Process crashes** — All cron jobs stop. No restart mechanism.
2. **Unhandled promise rejection** — Job throws, process might crash.
3. **Memory leak** — Long-running process gradually consumes more memory.

## Monitoring Bull / BullMQ

Bull is a Redis-backed job queue with repeatable jobs. It's more resilient than in-process scheduling but has its own failure modes.

### Setup

```javascript
const Queue = require('bull');

const emailQueue = new Queue('emails');

// Add repeatable job
await emailQueue.add('send-daily', {}, {
  repeat: { cron: '0 2 * * *' },
  removeOnComplete: 100,
  removeOnFail: 50
});

// Monitor job processing (monitored() is defined above)
emailQueue.process('send-daily', () => monitored('bull-send-daily', sendDailyEmails));

// Monitor queue health
emailQueue.on('failed', (job, error) =>
  send('event', { type: 'bull.job_failed', severity: 'warning', payload: { job: job.id, error: error.message } }));
```

### Watch for Redis Connection Issues

```javascript
emailQueue.on('error', () =>
  send('event', { type: 'bull.redis_error', severity: 'critical', payload: { error: 'Redis connection lost' } }));
```

### Common Failures

1. **Redis connection lost** — All jobs stop processing.
2. **Worker crashes mid-job** — Job stays in "active" state forever.
3. **Repeatable job disappears** — After Redis restart, repeatable jobs need re-registration.

## Monitoring PM2 Processes

If you use PM2 to manage Node.js processes, monitor the process health alongside your cron jobs.

```javascript
// ecosystem.config.js
module.exports = {
  apps: [{
    name: 'cron-worker',
    script: './cron-worker.js',
    max_memory_restart: '256M',
    watch: false,
    env: {
      NODE_ENV: 'production'
    }
  }]
};
```

```bash
# PM2 health check script
#!/bin/bash
# /usr/local/bin/pm2-health.sh

STATUS=$(pm2 jlist | jq -r '.[0].pm2_env.status')
NOW=$(date -u +%FT%TZ)
RESULT=completed; CODE=0
if [ "$STATUS" != "online" ]; then RESULT=failed; CODE=1; fi

curl -sS -m 5 -X POST "https://app.crontinel.com/api/v1/ingest/cron" \
  -H "Authorization: Bearer $CRONTINEL_INGEST_KEY" \
  -H "Content-Type: application/json" \
  -d "{\"command\":\"pm2-cron-worker\",\"status\":\"$RESULT\",\"exit_code\":$CODE,\"started_at\":\"$NOW\",\"finished_at\":\"$NOW\",\"output\":\"Process status: $STATUS\"}" || true
```

## HTTP check-in (supported path)

```javascript
await fetch('https://app.crontinel.com/api/v1/ingest/cron', {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${process.env.CRONTINEL_INGEST_KEY}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    request_key: 'run-1',
    command: 'my-task',
    status: 'completed',
    exit_code: 0,
    started_at: '2026-10-06T02:00:00Z',
    finished_at: '2026-10-06T02:00:04Z',
    outcomes: { metrics: { processed_records: 0 } },
  }),
});
```

Full recipes: [docs.crontinel.com/check-in/recipes/](https://docs.crontinel.com/check-in/recipes/).

## Quick Comparison

| Feature | node-cron | Bull/BullMQ | Agenda | Crontinel |
|---------|-----------|-------------|--------|-----------|
| Missed run detection | ❌ | ❌ | ❌ | ✅ |
| Duration tracking | ❌ | ❌ | ❌ | ✅ |
| Queue depth | N/A | ✅ | ✅ | ✅ |
| Auto-alerts | ❌ | ❌ | ❌ | ✅ |
| Works with all schedulers | ✅ | ✅ | ✅ | ✅ |
| Redis connection monitoring | N/A | ✅ | ✅ | ✅ |
