Cron expressions are powerful tools in Unix/Linux systems for defining when scheduled tasks should execute. Whether for system maintenance, data backup, or automated script execution, Cron is an indispensable tool. This guide provides an in-depth look at Cron expression syntax, principles, and best practices.
Table of Contents
- Key Takeaways
- What is Cron?
- Cron Expression Syntax
- Common Cron Expression Examples
- Code Examples
- Best Practices
- Frequently Asked Questions
- Conclusion
Key Takeaways
- Five/Six Field Format: Standard Cron uses 5 fields, extended versions support 6 or 7 fields (including seconds and year)
- Flexible Time Definition: Supports exact times, ranges, lists, step values, and more
- Wide Application: Supported by Linux systems and various programming languages and frameworks
- Timezone Sensitive: Cron task execution time depends on system timezone settings
- Error-Prone: Complex Cron expressions are easy to get wrong, use tools to validate
Need to quickly generate or validate Cron expressions? Try our free online tool:
Try Cron Expression Generator Now
What is Cron?
Cron is a time-based job scheduler daemon in Unix/Linux systems, used to automatically execute tasks at specified times. Cron expressions are the string format used to define task execution times.
Main uses of Cron include:
- System Maintenance: Regular cleanup of logs, temporary files
- Data Backup: Scheduled database and filesystem backups
- Report Generation: Periodic business report generation
- Monitoring Alerts: Regular system status checks
- Automated Deployment: Scheduled code pulls, service restarts
Cron Expression Syntax
Basic Format
Standard Cron expressions consist of 5 fields separated by spaces:
┌───────────── minute (0-59)
│ ┌───────────── hour (0-23)
│ │ ┌───────────── day of month (1-31)
│ │ │ ┌───────────── month (1-12)
│ │ │ │ ┌───────────── day of week (0-7, both 0 and 7 represent Sunday)
│ │ │ │ │
* * * * *
Extended format (6 fields, including seconds):
┌───────────── second (0-59)
│ ┌───────────── minute (0-59)
│ │ ┌───────────── hour (0-23)
│ │ │ ┌───────────── day of month (1-31)
│ │ │ │ ┌───────────── month (1-12)
│ │ │ │ │ ┌───────────── day of week (0-7)
│ │ │ │ │ │
* * * * * *
Field Descriptions
| Field | Allowed Values | Allowed Special Characters |
|---|---|---|
| Second | 0-59 | , - * / |
| Minute | 0-59 | , - * / |
| Hour | 0-23 | , - * / |
| Day of Month | 1-31 | , - * / ? L W |
| Month | 1-12 or JAN-DEC | , - * / |
| Day of Week | 0-7 or SUN-SAT | , - * / ? L # |
Special Characters
| Character | Meaning | Example |
|---|---|---|
* |
Any value | * * * * * runs every minute |
, |
List | 1,15,30 * * * * runs at minutes 1, 15, 30 |
- |
Range | 0-30 * * * * runs minutes 0-30 |
/ |
Step | */5 * * * * runs every 5 minutes |
? |
No specific value | Used in day and weekday fields |
L |
Last | L * * * last day of month |
W |
Weekday | 15W * * * nearest weekday to 15th |
# |
Nth occurrence | 0 0 * * 5#3 third Friday of month |
Common Cron Expression Examples
| Expression | Description |
|---|---|
* * * * * |
Every minute |
0 * * * * |
Every hour on the hour |
0 0 * * * |
Every day at midnight |
0 0 * * 0 |
Every Sunday at midnight |
0 0 1 * * |
First day of every month at midnight |
0 0 1 1 * |
January 1st at midnight |
*/5 * * * * |
Every 5 minutes |
0 */2 * * * |
Every 2 hours |
0 9-18 * * 1-5 |
Hourly 9AM-6PM on weekdays |
0 0 15 * * |
15th of every month at midnight |
30 4 1,15 * * |
1st and 15th at 4:30 AM |
0 22 * * 1-5 |
Weekdays at 10 PM |
Code Examples
Linux Crontab
# Edit current user's crontab
crontab -e
# View current user's crontab
crontab -l
# Remove current user's crontab
crontab -r
# Example: Run backup script at 2 AM daily
0 2 * * * /home/user/backup.sh
# Example: Check service status every 5 minutes
*/5 * * * * /home/user/check_service.sh
# Example: Send report at 9 AM on weekdays
0 9 * * 1-5 /home/user/send_report.sh
# Redirect output to log file
0 * * * * /home/user/script.sh >> /var/log/script.log 2>&1
Node.js
// Using node-cron library
// npm install node-cron
const cron = require('node-cron');
// Run every minute
cron.schedule('* * * * *', () => {
console.log('Running every minute');
});
// Run at 9 AM daily
cron.schedule('0 9 * * *', () => {
console.log('Running at 9 AM');
});
// Run every 5 minutes
cron.schedule('*/5 * * * *', () => {
console.log('Running every 5 minutes');
});
// Run hourly on weekdays
cron.schedule('0 * * * 1-5', () => {
console.log('Running hourly on weekdays');
});
// Validate Cron expression
const isValid = cron.validate('0 0 * * *');
console.log('Expression valid:', isValid);
Python
# Using APScheduler library
# pip install apscheduler
from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.triggers.cron import CronTrigger
def my_job():
print('Job executing...')
scheduler = BlockingScheduler()
# Run every minute
scheduler.add_job(my_job, CronTrigger.from_crontab('* * * * *'))
# Run at 9 AM daily
scheduler.add_job(my_job, CronTrigger(hour=9, minute=0))
# Run every 5 minutes
scheduler.add_job(my_job, CronTrigger(minute='*/5'))
# Run hourly on weekdays
scheduler.add_job(my_job, CronTrigger(hour='*', day_of_week='mon-fri'))
# Using croniter to parse Cron expressions
# pip install croniter
from croniter import croniter
from datetime import datetime
cron = croniter('0 9 * * *', datetime.now())
next_run = cron.get_next(datetime)
print(f'Next run time: {next_run}')
scheduler.start()
Java
// Using Spring @Scheduled annotation
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class ScheduledTasks {
// Run every minute
@Scheduled(cron = "0 * * * * *")
public void everyMinute() {
System.out.println("Running every minute");
}
// Run at 9 AM daily
@Scheduled(cron = "0 0 9 * * *")
public void everyDayAt9AM() {
System.out.println("Running at 9 AM");
}
// Run every 5 minutes
@Scheduled(cron = "0 */5 * * * *")
public void every5Minutes() {
System.out.println("Running every 5 minutes");
}
// Run hourly on weekdays
@Scheduled(cron = "0 0 * * * MON-FRI")
public void weekdaysHourly() {
System.out.println("Running hourly on weekdays");
}
}
Best Practices
1. Timezone Handling
# Set timezone in crontab
CRON_TZ=America/New_York
0 9 * * * /home/user/script.sh
2. Error Handling and Logging
# Redirect both stdout and stderr to log
0 * * * * /home/user/script.sh >> /var/log/cron.log 2>&1
# Log errors only
0 * * * * /home/user/script.sh 2>> /var/log/cron_error.log
3. Prevent Task Overlap
# Use flock to prevent overlapping execution
*/5 * * * * flock -n /tmp/script.lock /home/user/script.sh
4. Environment Variables
# Set environment variables in crontab
PATH=/usr/local/bin:/usr/bin:/bin
SHELL=/bin/bash
MAILTO=admin@example.com
0 * * * * /home/user/script.sh
5. Testing and Validation
- Use online tools to validate Cron expressions
- Test with short intervals first, then change to production intervals
- Check system logs to confirm task execution
Frequently Asked Questions
What if my Cron task isn't running?
- Check if cron service is running:
systemctl status cron - Verify crontab syntax is correct
- Check script permissions:
chmod +x script.sh - Verify script path is correct (use absolute paths)
- Check system logs:
grep CRON /var/log/syslog
How do I handle timezone issues?
Cron uses the system timezone by default. For other timezones:
- Set
CRON_TZenvironment variable in crontab - Or handle timezone conversion in your script
What's the difference between 0 and 7 in the weekday field?
In most systems, both 0 and 7 represent Sunday. It's recommended to consistently use 0 for Sunday, or use English abbreviations (SUN, MON, etc.) for better readability.
How do I implement second-level scheduling?
Standard crontab doesn't support second-level scheduling. You can use:
- Extended Cron formats (like Spring's @Scheduled)
- Sleep in your script
- Professional task scheduling frameworks
Conclusion
Cron expressions are core tools for Linux system administration and automation. Mastering Cron expression syntax and best practices helps you achieve precise, reliable scheduled task execution.
Quick Summary:
- Standard Cron uses 5 fields: minute, hour, day, month, weekday
- Special characters (*, ,, -, /) provide flexible time definitions
- Pay attention to timezone settings and environment variables
- Use logging and error handling for reliable task execution
- Use tools to validate complex Cron expressions
Need to quickly generate or validate Cron expressions? Try our free online tool: