Linux Tutorial — Part 8: Cron Jobs & Task Scheduling

By Suraj Ahir December 13, 2025 6 min read

Linux — Disk & Storage
Linux — Disk & Storage
← Part 7 Linux Tutorial · Part 8 of 12 Part 9 →

Production systems need to do things automatically on a schedule — run backups at midnight, send reports every Monday, clean up logs every Sunday, check server health every 5 minutes. Cron is Linux's built-in task scheduler, and it is one of the most practically useful tools in system administration.

Understanding Cron

Cron is a daemon (background process) that wakes up every minute and checks a set of configuration files called crontabs. If any job is scheduled for the current time, cron runs it. The service starts automatically at boot and runs continuously.

Crontab Syntax

Cron Schedule Format
# Format: minute hour day-of-month month day-of-week command
#         *      *    *            *     *
#         |      |    |            |     |--- Day of week (0-7, 0 and 7 are Sunday)
#         |      |    |            |--------- Month (1-12)
#         |      |    |---------------------- Day of month (1-31)
#         |      |--------------------------- Hour (0-23)
#         |---------------------------------- Minute (0-59)

# Examples:
0 2 * * *       /backup.sh         # Every day at 2:00 AM
*/5 * * * *     /health-check.sh   # Every 5 minutes
0 9 * * 1       /weekly-report.sh  # Every Monday at 9 AM
0 */6 * * *     /sync.sh           # Every 6 hours
0 0 1 * *       /monthly-cleanup.sh # First day of every month at midnight
30 18 * * 1-5   /eod-backup.sh     # Weekdays at 6:30 PM

Managing Crontabs

Crontab Commands
crontab -e          # Edit current user's crontab
crontab -l          # List current crontab
crontab -r          # Remove crontab (careful!)
sudo crontab -e     # Edit root's crontab
crontab -u username -l  # View another user's crontab

Practical Cron Examples

Real Cron Jobs
# Check disk usage every 10 minutes, alert if over 85%
*/10 * * * * df / | awk 'NR==2 {gsub(/%/,""); if($5>85) print "DISK ALERT: "$5"%"}' | mail -s "Disk Alert" admin@srjahir.in

# Daily backup at 3 AM
0 3 * * * /home/suraj/scripts/backup.sh >> /var/log/backup.log 2>&1

# Restart app if it crashes (every minute)
* * * * * systemctl is-active myapp || systemctl restart myapp

# Weekly log rotation every Sunday at midnight
0 0 * * 0 find /var/log/myapp -name "*.log" -mtime +30 -delete

# Database backup every 6 hours
0 */6 * * * /usr/local/bin/pg_backup.sh

Systemd Timers — The Modern Alternative

Systemd timers are a more modern alternative to cron with better logging and dependency management:

Systemd Timer Unit
# /etc/systemd/system/backup.timer
[Unit]
Description=Daily Backup Timer

[Timer]
OnCalendar=daily
Persistent=true

[Install]
WantedBy=timers.target

# Enable and start
sudo systemctl enable backup.timer
sudo systemctl start backup.timer
sudo systemctl list-timers

Viewing Cron Logs

Cron Logging
grep CRON /var/log/syslog           # See cron execution history
tail -f /var/log/syslog | grep CRON # Follow cron activity
journalctl -u cron                  # Systemd journal for cron

Best Practices for Cron Jobs

A few important practices that prevent common cron problems: Always use absolute paths in cron scripts, because cron runs with a minimal environment and may not have your normal PATH. Redirect output to a log file with >> logfile 2>&1 so you can diagnose failures. Test scripts manually before scheduling them. Add flock or locking if the same job might run while a previous instance is still running — this prevents overlapping executions causing data corruption.

In Part 9, we will cover package management — how to install, update, and manage software on Linux systems.

Cron Job Best Practices

Several practices make cron jobs reliable and debuggable. Always use absolute paths because cron runs with a minimal PATH that does not include your normal directories. Redirect both stdout and stderr to a log file: * * * * * /path/to/script.sh >> /var/log/myjob.log 2>&1. Use MAILTO="" at the top of crontab to suppress email output, or set it to your address to receive notifications. For long-running jobs, prevent overlapping executions using flock: * * * * * flock -n /tmp/myjob.lock /path/to/script.sh. Always test the exact command manually from the terminal first to verify it works before scheduling it.

Systemd Timers as a Modern Alternative

Systemd timers offer advantages over cron: better logging via journalctl, dependency management, and the ability to catch up on missed jobs after system downtime. A timer requires two unit files — a service file defining what to run, and a timer file defining when. Use systemctl list-timers to see all scheduled timers and their next execution times. For new systems where systemd is available, timers are worth learning as the modern alternative, while cron remains universal and will work everywhere.

at Command for One-Time Jobs

While cron handles recurring jobs, the at command schedules a one-time job to run at a specific future time. at 3pm tomorrow opens an interactive prompt where you type commands, then press Ctrl+D to submit. at now + 2 hours schedules something two hours from now. atq lists pending at jobs and atrm removes them. The at command is useful for one-off maintenance tasks — running a database backup before a system update, sending a notification at a specific time, or running a script during a low-traffic window.

Practice Exercise

Create a cron job that runs every minute and appends the current timestamp and disk usage to a log file. Let it run for five minutes, then examine the log. Verify the cron job is running with crontab -l. After verifying it works, change the schedule to run daily at midnight. Then remove it with crontab -e and delete the line. Also practice using at now + 5 minutes to schedule a one-time command and verify it ran with atq before it executes.

Linux in Your Daily Engineering Practice

Linux command-line proficiency is not something you learn once and then stop improving. It is a skill that deepens continuously as you encounter new tools, new use cases, and new problems to solve. The engineers who are most effective at the command line did not become that way by reading comprehensive guides — they became that way by spending years solving real problems at the terminal, gradually accumulating a toolkit of commands, aliases, scripts, and muscle memory. The best approach is to use Linux for real work as much as possible, to look up better ways to do things you already do, and to make note of efficient patterns you observe in others' work. Over time, the terminal becomes faster than any GUI for the tasks you do repeatedly.

Disclaimer: Educational content only. Practice is required for real skill development.