The Definitive Cron Jobs Syntax Cheat Sheet: Master Scheduling Tasks in Linux

Introduction to Cron Jobs

Cron is a time-based job scheduler in Unix-like operating systems that enables users to schedule commands or scripts to run automatically at specified intervals. Cron jobs are defined in a crontab (cron table) file, which contains instructions for the cron daemon about when and how often to run specific tasks. Mastering cron syntax allows system administrators, developers, and power users to automate routine tasks, schedule backups, run maintenance scripts, and ensure critical processes execute reliably without manual intervention.

Cron Syntax Fundamentals

Basic Crontab Format

* * * * * command_to_execute
↑ ↑ ↑ ↑ ↑
│ │ │ │ │
│ │ │ │ └── Day of the week (0-6 or SUN-SAT)
│ │ │ └──── Month (1-12 or JAN-DEC)
│ │ └────── Day of the month (1-31)
│ └──────── Hour (0-23)
└────────── Minute (0-59)

Understanding Time Fields

Field PositionField NameValuesSpecial Characters
1Minute0-59*, /, -, ,
2Hour0-23*, /, -, ,
3Day of Month1-31*, /, -, , ? L W
4Month1-12 or JAN-DEC*, /, -, ,
5Day of Week0-6 or SUN-SAT*, /, -, , ? L #
6Year (optional)1970-2099*, /, -, ,

Special Characters Explained

CharacterNameDescriptionExample
*AsteriskMatches all values in the field* * * * * = Run every minute
/SlashSpecifies step values*/15 * * * * = Run every 15 minutes
HyphenDefines ranges0-5 * * * * = Run in first 6 minutes of every hour
,CommaSeparates multiple values1,15,30 * * * * = Run at 1st, 15th, and 30th minute
LLastLast day of month or week* * L * * = Run on last day of the month
WWeekdayNearest weekday to the given day* * 15W * * = Run on nearest weekday to the 15th
#HashNth day of the month* * * * 5#3 = Run on third Friday of the month
?Question markNo specific value (used in some implementations)* * * * ? = No specific day of week

Common Cron Job Examples

Time-Based Schedules

ScheduleCron ExpressionDescription
Every minute* * * * *Run every minute of every hour, every day
Every 5 minutes*/5 * * * *Run every 5th minute (0, 5, 10, 15…)
Every hour0 * * * *Run at the start of every hour
Every 2 hours0 */2 * * *Run every 2 hours, starting at midnight
Twice daily0 0,12 * * *Run at midnight and noon every day
Daily at 3:15 AM15 3 * * *Run at 3:15 AM every day
Weekdays at 9 AM0 9 * * 1-5Run at 9 AM Monday through Friday
Weekends at 8:30 PM30 20 * * 0,6Run at 8:30 PM on Saturday and Sunday
First day of month0 0 1 * *Run at midnight on the first of every month
Every quarter0 0 1 1,4,7,10 *Run at midnight on first day of each quarter
Every 6 months0 0 1 1,7 *Run at midnight on January 1 and July 1
Yearly on Dec 3159 23 31 12 *Run at 11:59 PM on December 31

Special Schedules

DescriptionCron ExpressionExplanation
Every reboot@rebootRun once at system startup
Every hour@hourlySame as 0 * * * *
Daily@dailySame as 0 0 * * *
Weekly@weeklySame as 0 0 * * 0
Monthly@monthlySame as 0 0 1 * *
Yearly@yearlySame as 0 0 1 1 *
Annually@annuallySame as @yearly

System-Wide vs. User Crontabs

User Crontabs

  • Location: Generally stored in /var/spool/cron/crontabs/
  • Access Command: crontab -e (edit), crontab -l (list), crontab -r (remove)
  • Permissions: Runs with the permissions of the specified user
  • Format: Does not include a username field

System-Wide Crontabs

  • Main System Crontab: /etc/crontab
  • Cron Directories:
    • /etc/cron.d/ – System job fragments
    • /etc/cron.daily/ – Daily jobs
    • /etc/cron.hourly/ – Hourly jobs
    • /etc/cron.monthly/ – Monthly jobs
    • /etc/cron.weekly/ – Weekly jobs
  • Format: Includes a username field to specify which user should run the command
    * * * * * username command_to_execute
    

Crontab Commands and Management

Essential Crontab Commands

CommandDescriptionExample
crontab -eEdit current user’s crontabcrontab -e
crontab -lList current user’s crontab entriescrontab -l
crontab -rRemove current user’s crontabcrontab -r
crontab -vDisplay the last time you edited your crontabcrontab -v
crontab file.txtInstall crontab from filecrontab mycron.txt
crontab -e -u usernameEdit another user’s crontab (requires sudo)sudo crontab -e -u john

Environment Variables in Crontabs

Cron jobs run with a minimal environment. Add these variables to your crontab for proper execution:

SHELL=/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=user@example.com
HOME=/home/username
  • SHELL: Defines which shell to use
  • PATH: Sets the search path for commands
  • MAILTO: Where to send output (empty string means no mail)
  • HOME: Sets the home directory

Advanced Cron Techniques

Redirecting Output

TechniqueExampleDescription
Discard all output0 * * * * command > /dev/null 2>&1Silences all output and errors
Log to file0 * * * * command > /path/to/log.txt 2>&1Redirects output and errors to a log file
Append to log0 * * * * command >> /path/to/log.txt 2>&1Appends output to existing log file
Log errors only0 * * * * command > /dev/null 2> /path/to/errors.logOnly logs error messages
Email output`0 * * * * commandmail -s “Cron Output” user@example.com`

Multiple Commands in One Line

# Run multiple commands sequentially
0 5 * * * command1 && command2 && command3

# Run commands regardless of previous command success
0 5 * * * command1; command2; command3

# Run second command only if first fails
0 5 * * * command1 || command2

Using Predefined Schedules

# Create reusable variables
DAILY="0 0 * * *"
WEEKLY="0 0 * * 0"

# Use them in crontab
$DAILY /scripts/daily-backup.sh
$WEEKLY /scripts/weekly-report.sh

Common Cron Job Use Cases

System Maintenance

# Clear temp files daily at 2:30 AM
30 2 * * * find /tmp -type f -atime +7 -delete

# Update package lists weekly on Sunday
0 0 * * 0 apt-get update

# Rotate logs monthly
0 0 1 * * /usr/sbin/logrotate /etc/logrotate.conf

Backups

# Daily database backup at 1 AM
0 1 * * * mysqldump -u user -p'password' database > /backups/db-$(date +\%Y\%m\%d).sql

# Weekly file backup on Saturday at 2 AM
0 2 * * 6 tar -czf /backups/home-$(date +\%Y\%m\%d).tar.gz /home/user

# Monthly cloud sync on the 1st at 3 AM
0 3 1 * * rsync -avz /backups/ user@remote:/backups/

Website & Application Maintenance

# Check website availability every 5 minutes
*/5 * * * * curl -s http://example.com > /dev/null || mail -s "Website Down" admin@example.com

# Clean sessions daily
0 1 * * * find /var/www/sessions -type f -mtime +1 -delete

# Generate sitemap weekly
0 3 * * 0 /var/www/html/generate-sitemap.php

Report Generation

# Generate daily traffic report
0 7 * * * /scripts/traffic-report.sh > /reports/traffic-$(date +\%Y\%m\%d).txt

# Email monthly financial summary
0 8 1 * * /scripts/financial-summary.sh | mail -s "Monthly Financial Report" finance@example.com

Troubleshooting Cron Jobs

Common Issues and Solutions

IssuePossible CausesSolutions
Job doesn’t runSyntax errors, path issues, permissionsCheck syntax, use absolute paths, ensure proper permissions
No output receivedOutput redirection, missing MAILTOCheck redirection, set MAILTO variable, verify mail setup
Incorrect timingTimezone differences, misunderstanding syntaxVerify system timezone, check cron syntax carefully
Command works manually but not in cronEnvironment variables, relative pathsUse absolute paths, set environment variables in crontab
Sporadic failuresResource constraints, timing conflictsAdd error handling, stagger job timing, monitor resource usage

Debugging Tips

  • Add timestamp output to help track execution:

    * * * * * echo "Job ran at $(date)" >> /tmp/cronjob.log && /path/to/actual/script
    
  • Test scripts separately before adding to crontab:

    $ sh -x /path/to/script.sh
    
  • Check cron logs for errors:

    $ grep CRON /var/log/syslog
    
  • Verify cron service is running:

    $ systemctl status cron
    
  • Use a crontab validator to check syntax:

    $ crontab -e && echo "Syntax OK"
    

Cron Security Best Practices

  • Use the principle of least privilege (run jobs as non-root users when possible)
  • Avoid placing sensitive information like passwords directly in crontab
  • Use restricted shell or specific commands to limit what cron can execute
  • Implement proper file permissions on scripts run by cron
  • Review crontabs regularly to remove unnecessary jobs
  • Log and monitor cron job activity
  • Consider using secret management tools instead of hardcoded credentials

Cron Alternatives and Extensions

ToolPlatformKey FeaturesBest For
AnacronLinuxRuns missed jobs after system downtimeSystems that aren’t always on
Systemd TimersLinuxProvides better logging, dependency managementModern Linux distributions
FcronLinuxHandles system downtime, supports load balancingSystems with variable load
CronieLinuxStandard cron implementation with PAM supportEnterprise Linux distributions
Task SchedulerWindowsWindows equivalent of cronWindows environments
JenkinsCross-platformAdvanced scheduling, web interface, pluginsComplex job orchestration
AirflowCross-platformWorkflow management, dependencies, retriesData pipeline scheduling
Kubernetes CronJobsKubernetesContainer-based job schedulingContainerized environments

Resources for Further Learning

Documentation

  • Man pages: man cron, man crontab, man 5 crontab
  • GNU Coreutils documentation
  • Linux System Administrator’s Guide

Online Tools

Books

  • “Linux Administration: A Beginner’s Guide” by Wale Soyinka
  • “UNIX and Linux System Administration Handbook” by Evi Nemeth et al.
  • “Pro Linux System Administration” by James Turnbull

Websites & Blogs

  • The Linux Documentation Project (TLDP)
  • DigitalOcean Community Tutorials
  • LinuxJournal
  • ServerFault Q&A

By mastering the cron syntax and best practices outlined in this cheat sheet, you’ll be able to efficiently automate tasks, maintain system health, and ensure critical operations run smoothly and reliably on your Linux systems.

Scroll to Top