What Is a Cron Job in Linux? Complete Guide with Examples
A cron job is a command scheduled by a running cron daemon on a Linux host. Use it for recurring maintenance, reports or a script that already works when run as its intended user. Cron starts commands at matching times; it does not guarantee completion, retry failures or recover every run missed while the host was down.
Read a cron schedule correctly
A user crontab has five time fields followed by a command. System files such as /etc/crontab and /etc/cron.d/* normally add a username before the command. Do not paste that extra username into crontab -e.
# minute hour day-of-month month day-of-week command
30 2 * * * /home/backup/bin/nightly-backup
*/30 * * * * /home/report/bin/refresh-report
0 9 * * 1-5 /home/report/bin/weekday-reportThe examples run daily at 02:30, at minutes 0 and 30 each hour, and at 09:00 Monday–Friday in the scheduler’s effective timezone. */30 is a field pattern, not a promise to wait 30 minutes after the previous completion. See the every-30-minutes guide for that distinction.
When both day-of-month and day-of-week are restricted, traditional cron/Cronie runs when either matches. Thus 0 9 1 * 1 is not “the first Monday.” Last-Friday schedules need an explicitly tested date condition or a scheduler supporting that calendar expression. Check the manual for your installed implementation, including its timezone and daylight-saving behavior.
Timezone extensions such as CRON_TZ are not universal. DST can skip or repeat wall-clock times; some daemon versions compensate for particular schedules. Use UTC when appropriate and test local business-calendar requirements. @reboot, where supported, means daemon startup, not proof that networking or a database is ready. Use service dependencies for startup ordering.
Install a job with an explicit environment
Inspect existing entries with crontab -l, retain a private backup if entries exist, then edit with crontab -e as the account that should execute the job. Use the least-privileged account with the required file permissions. A user crontab might contain:
SHELL=/bin/sh
PATH=/usr/local/bin:/usr/bin:/bin
MAILTO=""
*/30 * * * * /home/report/bin/run-report >> /home/report/log/report.log 2>&1These are illustrative absolute paths: create the script and log directory for the actual account first. The shell must be able to open the log before the job can start. MAILTO="" disables cron mail in this example; it does not configure another alert channel. Without that setting, mail delivery still depends on a working mail system. Cron commonly mails command output, not every nonzero exit code.
Interactive shell startup files are not a reliable dependency. Set required variables explicitly or load a reviewed, access-restricted configuration file in the script. Never print a complete environment or enable shell tracing around secrets. Keep percent signs inside scripts where possible: an unescaped % in a crontab command has special meaning in common cron implementations.
Prevent overlap with a real lock
Checking whether a file exists and then creating it is racy. On Linux, flock provides an advisory lock released when its file descriptor closes. All competing instances must use the same lock. Use a directory owned by the job account on a local filesystem; review network-filesystem locking separately.
Create /home/report/bin, /home/report/run and /home/report/log with suitable ownership. This Bash wrapper runs an existing report program, logs its outcome, and returns its actual exit code:
#!/usr/bin/env bash
set -u
umask 077
export PATH=/usr/local/bin:/usr/bin:/bin
cd /home/report || exit 1
exec 9>/home/report/run/report.lock || exit 1
if ! flock -n 9; then
printf '%s report skipped: another instance is running
' "$(date -u +%FT%TZ)" >&2
exit 75
fi
printf '%s report started
' "$(date -u +%FT%TZ)"
if /home/report/bin/build-report; then
rc=0
else
rc=$?
fi
printf '%s report finished exit=%s
' "$(date -u +%FT%TZ)" "$rc"
exit "$rc"Give the wrapper executable permission, for example chmod 750 /home/report/bin/run-report, and make it owned by the intended account. The lock stays held while the foreground program runs. Do not background that program or delete the lock file while jobs may be running. Exit 75 makes a skipped overlap visible to a wrapper/monitor; cron itself does not retry it automatically.
Decide what a timeout means for the operation before adding one. Killing a database restore or file transfer can leave partial work. Idempotency, atomic output files and application-level transactions are more useful than blindly retrying every failure.
Backups and cleanup need their own acceptance checks
A schedule does not make a backup valid. Use a separately tested backup program with credentials in a protected supported configuration or secret mechanism, never a database password embedded in the cron command. Write to a temporary output, propagate pipeline failures, validate the result, and promote it atomically where possible. Preserve previous recovery points until the new one is accepted. A backup job’s zero exit code is still not a substitute for a restore test.
Database consistency depends on the engine and backup method. Select the database vendor’s documented snapshot or dump procedure, including its locking and concurrent-DDL limitations, rather than combining an unreviewed dump, compression and deletion command.
For logs, use the logrotate workflow and one clear scheduling owner per rule. A broad find /var/log -name '*.log' -delete can remove active logs and is not a safe rotation policy. For any retention task, list the exact candidates first, constrain the directory and file types, and confirm that recovery requirements permit deletion.
Test before relying on the schedule
- Run the script as the cron account, from its intended working directory, with only its documented environment. Confirm outputs and permissions.
- Use harmless test data and force a controlled nonzero exit. Verify the wrapper retains the exit status and the log explains the failure without secrets.
- Start two test instances. Confirm the second cannot perform the protected work and that the skip is observable.
- Schedule a short-lived test entry. Confirm the daemon starts it, then remove that test entry without disturbing existing jobs.
- Test missed-run detection independently by intentionally withholding a test check-in. Restore the test schedule and confirm recovery notification.
Inspect the applicable cron service and its journal/syslog on your distribution. The service is commonly named cron or crond; identify it before using a command copied from another distro. Daemon logs prove dispatch at most, while application logs and outputs establish completion. For diagnosis, see cron jobs not running.
If a job is dangerous, disable its specific schedule and follow the application’s cancellation procedure for the already-running instance. Removing an entry does not stop a running process. Avoid stopping all cron jobs or using a broad process-name kill as a routine fix.
Monitor completion and missed runs
Fivenines cron monitoring can provide an independent check-in and missed-run signal. Use the exact success/failure URLs and semantics supplied by the monitor configuration, keep them secret, and send success only after the job’s result is accepted. Set the expected interval and grace period to the real schedule and runtime. Alert delivery and recovery must be tested with a disposable job before depending on them.
Separate execution failure from notification failure: a successful backup with a failed check-in and a failed backup with a successful HTTP request are different outcomes. Keep the application’s exit status and bounded network timeouts. Compare scheduling and monitoring requirements when choosing infrastructure monitoring tools.
When missed-run catch-up, dependencies or structured service management matter, evaluate a systemd timer. Persistent=true can trigger a missed calendar timer on activation; it does not replay every missed occurrence or make the job idempotent. Choose the scheduler for the operational behavior you need, then verify that behavior.

