๐ ุงูุฑุฃ ูุฐุง ุงูุฏููู ุจุงููุบุฉ ุงูุนุฑุจูุฉ (Read this guide in Arabic) โ
What Is a Cron Job?
A cron job is an automated task that runs a command or script at a scheduled time or interval.
Cron is the scheduler; a cron job is the scheduled task; and a crontab is the configuration that tells cron what to run and when.
In modern web development, backend engineering, and system administration, servers rely on recurring background jobs to handle tasks like generating database backups, pruning expired cache files, processing billing subscriptions, and dispatching summary emails.
| Term | Meaning | Role in Linux |
|---|---|---|
| Cron | The time-based scheduler / background daemon (crond) | Executes the tasks |
| Cron job | The individual command or script scheduled to run | The task being performed |
| Crontab | The configuration table containing scheduled jobs | The schedule definition |
1. How Does a Cron Job Work?
Every minute, the cron service (crond) wakes up and checks scheduled entries in your system's crontab files. When the current system time and date match a scheduled rule, cron launches and executes the specified command in the background.
How the Cron Daemon Works
[ crond Daemon (PID 1) ]
โ
โผ (Wakes every 60 seconds)
[ Read /etc/crontab & user tables ]
โ
โโโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโ
โผ โผ
No Match: Match Found:
Sleep to next min. fork() -> exec(sh -c)
The daemon reads configuration tables called crontabs (short for "cron tables"). Each line in a crontab defines a specific schedule expression and the command or shell script to execute when that schedule triggers.
2. Common Uses of Cron Jobs
System administrators and developers use cron jobs across backend infrastructure to automate repetitive maintenance:
- Database Backups: Dumping PostgreSQL or MySQL databases to Amazon S3 or cloud storage every night at
02:00 AM. - Billing & Subscriptions: Processing daily recurring subscription charges and payment gateway webhooks.
- Log Rotation: Compressing and archiving
/var/logfiles weekly to prevent disk space (ENOSPC) exhaustion. - Cache Pruning: Deleting expired Redis session keys and temporary files every hour.
- Email Digests: Sending daily summary reports to users at
08:00 AMlocal time. - SSL Certificate Renewal: Running
certbot renewtwice daily to ensure Let's Encrypt certificates never expire.
3. Cron Job Syntax Explained
Every cron job entry in a crontab is formatted as a 5-field cron expression followed by the target shell command:
โโโโโโโโโโโโโโโโ Minute (0 - 59)
โ โโโโโโโโโโโโโโ Hour (0 - 23)
โ โ โโโโโโโโโโโโ Day of Month (1 - 31)
โ โ โ โโโโโโโโโโ Month (1 - 12 or JAN - DEC)
โ โ โ โ โโโโโโโโ Day of Week (0 - 6 or SUN - SAT, 0 = Sunday)
โ โ โ โ โ
* * * * * /usr/local/bin/backup-database.sh
The 4 Core Cron Operators
| Operator | Name | Purpose | Example | Explanation |
|---|---|---|---|---|
* | Asterisk | Matches every possible value in that field | * in Hour | Runs every hour of the day |
, | Comma | Defines a discrete list of values | 15,45 in Minute | Runs at minute 15 and minute 45 |
- | Hyphen | Defines an inclusive range of values | 1-5 in Day of Week | Runs Monday through Friday |
/ | Slash | Defines step intervals | */15 in Minute | Runs every 15 minutes (0, 15, 30, 45) |
4. Common Cron Job Examples (Copy-Paste Cheat Sheet)
Here are the most common cron expressions used in production:
| Schedule | Cron Expression | Command Example |
|---|---|---|
| Every minute | * * * * * | * * * * * /usr/local/bin/healthcheck.sh |
| Every 5 minutes | */5 * * * * | */5 * * * * /usr/local/bin/check-queue.sh |
| Every hour (at minute 0) | 0 * * * * | 0 * * * * /usr/local/bin/sync-cache.sh |
| Every day at midnight | 0 0 * * * | 0 0 * * * /usr/local/bin/nightly-backup.sh |
| Every Sunday at 3:30 AM | 30 3 * * 0 | 30 3 * * 0 /usr/local/bin/rotate-logs.sh |
| Every weekday (MonโFri) at 9:00 AM | 0 9 * * 1-5 | 0 9 * * 1-5 /usr/local/bin/send-reports.sh |
| On the 1st of every month at 6:00 AM | 0 6 1 * * | 0 6 1 * * /usr/local/bin/process-invoices.sh |
๐ ๏ธ Free Visual Tools:
- Open Interactive Cron Expression Builder โ โ Build and test custom 5-field cron strings with visual dropdowns.
- Open Cron Expression Translator โ โ Convert any raw cron expression into plain English explanations instantly.
5. How to Create a Cron Job on Linux
To create and manage scheduled tasks on Linux or macOS, use the standard crontab utility in your terminal:
Step 1: Open Your Crontab
Run the following command to open your user's crontab in the default text editor:
crontab -e
(If this is your first time, the system will prompt you to select an editor like nano or vim).
Step 2: Add Your Schedule and Command
Scroll to the bottom of the file and add your 5-field expression followed by the absolute path to your script:
# Run database backup script every night at 2:00 AM
0 2 * * * /usr/local/bin/backup-database.sh
Step 3: Save and Exit the Editor
- In nano: Press
Ctrl + OthenEnterto save, followed byCtrl + Xto exit. - In vim: Press
Esc, type:wq, and hitEnter.
The system will confirm: crontab: installing new crontab.
Step 4: Verify Your Active Cron Jobs
List all scheduled tasks to confirm your job was added:
crontab -l
Step 5: Test the Command Manually
Before relying on automated execution, run the exact command directly in your terminal to verify that it executes without errors:
/usr/local/bin/backup-database.sh
echo $?
(An exit code of 0 indicates successful execution).
6. Why Did My Cron Job Not Run?
When a cron job does not execute as expected, it is usually caused by environmental differences between an interactive terminal and the background cron daemon.
Common Cron Failure Checklist
[ 1. Stripped PATH ] [ 2. Permissions ] [ 3. Relative Paths ] [ 4. Timezones ]
Cron runs minimal Missing chmod +x on Script looks for files Server runs in UTC;
/usr/bin:/bin. the executable script. in local directory. you expected local.
Diagnostic Checklist & Solutions:
- Stripped
PATHEnvironment: In an interactive terminal, your shell loads paths for Node.js, Python, or Docker from~/.bashrc. Cron runs with a barebonesPATH=/usr/bin:/bin. If your script callsnodeordocker, cron fails withcommand not found.
Fix: Use full absolute paths (/usr/bin/nodeor/usr/local/bin/docker) or definePATHat the top of your crontab. - Missing Execute Permissions: The script must be executable by the user running the crontab.
Fix: Runchmod +x /usr/local/bin/script.sh. - Relative File Paths: Cron executes commands with the userโs home directory (
$HOME) as the working directory, not the directory where your script is located.
Fix: Use absolute paths inside your scripts, or change directory before running:0 2 * * * cd /var/www/app && ./run-maintenance.sh - Missing Environment Variables: Cron does not source
.envfiles or user profiles. Database passwords and API keys will be missing.
Fix: Explicitly source the environment inside the script or command:0 2 * * * . /etc/environment && /usr/local/bin/backup.sh - Timezone Mismatches: Most cloud servers and virtual machines run on UTC time by default. If you schedule a job for
02:00 AMexpecting local time, it will run at02:00 UTC.
Fix: Check server timezone withtimedatectlor specifyCRON_TZ=America/New_Yorkat the top of the crontab. - Silent Failure & Missing Stderr: By default, if a cron job throws an error or exits with code
1, the output is discarded unless you have a local mail agent configured.
Fix: Redirectstdoutandstderrto a log file for debugging:0 2 * * * /usr/local/bin/backup.sh >> /var/log/backup.log 2>&1 - Overlapping Process Stampedes: If a script takes 15 minutes to run but is scheduled every 10 minutes, multiple instances will run concurrently, locking files and exhausting server memory.
Fix: Useflock(file lock) to prevent overlapping executions:*/10 * * * * /usr/bin/flock -n /tmp/backup.lock /usr/local/bin/backup.sh - Server Reboots During Scheduled Window: Cron does not have a queue. If your server is rebooting or offline at
02:00 AM, the job is skipped until the next day.
7. How to Monitor a Cron Job
Cron can tell your server to run a task, but it does not automatically notify you when that task fails, hangs, or crashes.
A heartbeat monitor (also known as a Dead Man's Switch) solves this by requiring your cron job to send an HTTP ping to an external monitoring service every time it completes successfully.
How Heartbeat Monitoring Works
[ Scheduled Cron Job ] โโ( Executes Successfully )โโ> [ Pingzo Heartbeat URL ]
โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โผ โผ
Heartbeat Received: Heartbeat Missed:
Job is Healthy (Reset Timer) Trigger Instant Outage Alert!
(WhatsApp, Telegram, Slack)
Implementing Heartbeat Monitoring with Pingzo in 3 Steps:
- Create a Heartbeat Endpoint: In Pingzo, create a new Heartbeat Monitor. Set your expected schedule (e.g., "Every day at 02:00 AM") and a grace period (e.g., 15 minutes). Pingzo gives you a unique endpoint URL.
- Append a 1-Line
curlto Your Crontab: Use the&&operator so that the ping is only sent if your script exits with code0(success):0 2 * * * /usr/local/bin/backup.sh && curl -fsS -m 10 --retry 3 https://www.pingzoapp.com/api/ping/YOUR_PING_TOKEN - Automated Incident Alerts:
- If the script crashes or returns an error, the
curlcommand never runs. - If the server goes offline or reboots, no ping arrives.
- If the script hangs past its grace period, the timer expires.
- Pingzo immediately sends an alert to your team via WhatsApp, Telegram, Slack, Discord, or Email.
- If the script crashes or returns an error, the
8. Cron vs. Systemd Timers
For modern Linux distributions (Ubuntu, Debian, RHEL, CentOS), systemd provides an alternative to cron known as Systemd Timers.
| Feature | Linux Cron (crond) | Systemd Timers (.timer) |
|---|---|---|
| Minimum Interval | 1 minute (60 seconds) | Sub-second (milliseconds) |
| Logging | Minimal syslog / local mail | Full structured logging via journalctl |
| Resource Limits | None (runs unconstrained) | Built-in cgroups (limit CPU, memory, IO) |
| Catch-up on Reboot | โ No (missed jobs are skipped) | โ
Yes (Persistent=true runs missed jobs) |
| Configuration Complexity | Simple (1 line in crontab) | Requires two files (.service and .timer) |
If your workloads require sub-minute execution or resource governance, read our deep-dive comparison:
๐ Sub-Minute Job Scheduling on Linux: Systemd Timers vs. Cron
9. Frequently Asked Questions (FAQ)
What is a cron job used for?
A cron job is used to automate recurring backend maintenance tasks, including nightly database backups, recurring billing and invoice generation, log rotation, cache clearing, and sending scheduled summary emails.
How do I create a cron job?
Run crontab -e in your Linux terminal to open your schedule table. Add a 5-field time expression followed by the command (e.g. 0 2 * * * /usr/local/bin/backup.sh), save the file, and verify it with crontab -l.
How do I check if a cron job is running?
To check if the cron service itself is active, run systemctl status cron (Debian/Ubuntu) or systemctl status crond (RHEL/CentOS). To see if a specific script is currently executing in the background, run pgrep -a -f script-name.sh or ps aux | grep script-name.sh.
How do I know if a cron job failed?
Because standard Linux cron does not feature built-in failure notifications, you can inspect execution output by redirecting stdout and stderr to a log file (>> /var/log/job.log 2>&1), or connect a Heartbeat Monitor that alerts you if the job fails to ping after completion.
What is the difference between cron and crontab?
Cron is the background daemon service (crond) that wakes up every minute to execute scheduled tasks. Crontab (cron table) is the configuration file or CLI command used to define and store the schedule rules for those tasks.
Can a cron job run every second?
No. The standard Unix cron daemon has a minimum granularity of 1 minute. For tasks requiring sub-minute execution (e.g. every 10 seconds), use Systemd monotonic timers or an application-level queue worker like BullMQ, Celery, or Sidekiq.
How do I run a cron job every 5 minutes?
Use the step operator (/) in the minute field: */5 * * * * /path/to/command.sh. This runs the command at minutes 0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, and 55 of every hour.
What happens if a cron job fails?
When a cron job encounters an error or exits with a non-zero exit code, cron terminates the process. Unless output redirection or external heartbeat monitoring is configured, the error is discarded silently without notifying the server administrator.
โก Protect Your Mission-Critical Cron Jobs Today
Never let a failed database backup or payment sync go unnoticed. Monitor your scheduled background jobs with Pingzo and receive instant, multi-channel outage alerts the second a job misses its scheduled run.
๐ Start Monitoring Cron Jobs with Pingzo โ
๐ ๏ธ Test Expressions with Free Cron Builder โ
Stop Finding Out About Outages from Angry Users
Get instant WhatsApp & Discord alerts the second your API, website, or server goes down. Setup in 30 seconds with 60-second checks.