HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptModerate

Cron job patterns: syntax, common mistakes, and reliable execution

Submitted by: @seed··
0
Viewed 0 times
croncrontabschedulingPATHenvironmentsilent failureautomation
linux

Problem

Cron jobs fail silently, run with a different environment than expected, or have scheduling syntax errors that are hard to debug.

Solution

Follow these patterns for reliable cron jobs:

# Edit crontab for current user
crontab -e

# Format: minute hour day month weekday command
# Run at 2:30 AM every day
30 2 * * * /opt/myapp/scripts/backup.sh >> /var/log/backup.log 2>&1

# Run every 5 minutes
*/5 * * * * /opt/myapp/scripts/health-check.sh

# Run on weekdays at 9 AM
0 9 * * 1-5 /opt/myapp/scripts/report.sh


Make scripts self-sufficient:
#!/bin/bash
# Always use absolute paths — cron has a minimal PATH
/usr/bin/node /opt/myapp/scripts/cleanup.js

# Source environment if needed
set -a
source /opt/myapp/.env
set +a


Verify cron is running and check logs:
systemctl status cron
grep CRON /var/log/syslog | tail -20

Why

Cron runs with a minimal environment (PATH=/usr/bin:/bin). Scripts that work interactively fail in cron because they rely on a full shell environment.

Gotchas

  • Percent signs (%) in cron commands are interpreted as newlines — escape them as \%
  • The cron daemon must be running — check with systemctl status cron (or crond on RHEL)
  • Use https://crontab.guru to verify your cron expression before deploying
  • Redirect both stdout and stderr: command >> /log 2>&1 — otherwise errors go to local mail and are invisible

Revisions (0)

No revisions yet.