Introduction to Scheduling and Linux Crontab Syntax
When you've written a Python scraper to "automatically fetch stock data" or a Node.js program to "automatically send account statements," you’ll inevitably face a problem: You can’t manually click to run it every day, can you?
This is where "automated scheduling (Cronjob / Scheduled Tasks)" comes into play.
What is a Scheduled Task (Cronjob)?
The concept of a scheduled task is simple—it’s like the "alarm" on your phone. You can set it to run at 8:00 AM every day, on the hour every hour, or at 3:00 PM every Monday, telling your computer: "When the time comes, please execute this code for me."
In the software engineering world, the most classic and widely used scheduling tool is the cron daemon built into Linux operating systems. The syntax and file we use to configure cron tasks are called Crontab (Cron Table).
The Magic of Crontab’s Five Stars
If you’ve ever seen someone’s scheduling configuration, you’ve likely encountered mysterious-looking code like this:
* * * * * /usr/bin/python3 /home/user/my_script.py
The seemingly cryptic "five stars" at the beginning are actually the essence of Crontab’s time definition. These five fields, from left to right, represent:
- Minute: 0 to 59
- Hour: 0 to 23
- Day of month: 1 to 31
- Month: 1 to 12
- Day of week: 0 to 7 (0 and 7 both represent Sunday)
Common Time Setting Examples
[!TIP] Don’t worry if you can’t memorize them! Engineers in the industry often use crontab.guru when writing Crontab. This website translates the five stars into human-readable language—super handy!
Here are some of the most commonly used real-world examples:
1. Run every minute
* * * * *
(Perfect for writing a ping script to ensure your server hasn’t crashed.)
2. Run every hour on the hour
0 * * * *
3. Run every day at 8:30 AM
30 8 * * *
(Great for sending "Good morning" greetings or "Today’s weather forecast" to a Line group.)
4. Run every Monday at 9:00 AM
0 9 * * 1
5. Run every 5 minutes (using a slash to denote frequency)
*/5 * * * *
Implementing Your First Crontab on Mac or Linux
If you’re using a Mac or any Linux system (including Raspberry Pi), cron is already built-in—you don’t need to install anything.
Step 1: Open the Crontab Editor
Open your Terminal and enter the following command to edit your schedule:
crontab -e
If it’s your first time running this, the system may ask which editor to use (e.g., Nano or Vim). Beginners are advised to choose Nano for its simplicity.
Step 2: Write the Schedule and Script Path
Suppose we have a Python script located at ~/Documents/auto_email.py, and we want it to run every night at 10:00 PM:
Add this line to the editor:
0 22 * * * /usr/bin/python3 ~/Documents/auto_email.py >> ~/Documents/cron_log.txt 2>&1
Breakdown:
0 22 * * *: Represents 22:00 (10:00 PM) every day./usr/bin/python3: Always use absolute paths in Crontab! The execution environment for Crontab differs from your Terminal, so it might not know wherepythonis located.~/Documents/auto_email.py: The path to your script.>> ~/Documents/cron_log.txt 2>&1: This is a highly practical advanced trick! By default, Crontab runs in the background, so if your program errors out, you won’t know. This command logs allprint()outputs and error messages tocron_log.txt, making debugging easier.
Step 3: Save and Exit
After saving the file, the Terminal will display:
crontab: installing new crontab
Congratulations! Your automated script is now live! As long as your computer stays on, the system will run your script every night at 10:00 PM sharp!
Why Do We Need to Learn Other Tools?
While Crontab is powerful, it has one critical flaw: Your computer must be on 24/7.
If you schedule tasks on your laptop, they won’t run once you close the lid. Renting a cloud server (VPS) for several hundred dollars a month just to run Crontab for a small script is overkill.
In the next chapters, we’ll teach you how to use completely free cloud scheduling tools to deploy your scripts to the cloud. This way, you won’t even need to keep your computer on—your scripts will work (or even earn money) for you 24/7!
Crontab Syntax Reference
The five fields in a cron expression each control a different time unit.
| Field | Range | Special Characters |
|-------|-------|-------------------|
| Minute | 0-59 | * , - / |
| Hour | 0-23 | * , - / |
| Day of Month | 1-31 | * , - / |
| Month | 1-12 or JAN-DEC | * , - / |
| Day of Week | 0-7 or SUN-SAT | * , - / |
Special Characters Explained
| Character | Meaning | Example | Description |
|-----------|---------|---------|-------------|
| * | Any/every | * * * * * | Every minute |
| , | List | 0 9,18 * * * | At 9:00 and 18:00 |
| - | Range | 0 9-17 * * * | Every hour from 9 to 17 |
| / | Step | */15 * * * * | Every 15 minutes |
Special Keywords
| Keyword | Equivalent | Meaning |
|---------|-----------|---------|
| @reboot | N/A | Runs once at system startup |
| @yearly | 0 0 1 1 * | Run once a year |
| @monthly | 0 0 1 * * | Run once a month |
| @weekly | 0 0 * * 0 | Run once a week |
| @daily | 0 0 * * * | Run once a day |
| @hourly | 0 * * * * | Run once an hour |
Common Cron Patterns
| Pattern | Schedule | Use Case |
|---------|----------|----------|
| 0 3 * * * | Daily at 3 AM | Nightly backups |
| */5 * * * * | Every 5 minutes | Monitoring checks |
| 0 0 * * 0 | Weekly at midnight Sunday | Report generation |
| 0 9 * * 1-5 | Weekdays at 9 AM | Business hour tasks |
| 0 0 1 * * | First day of month | Monthly billing |
| 0 0,12 * * * | Twice daily (midnight/noon) | Database sync |
| 30 2 * * 6 | Saturday at 2:30 AM | Weekly maintenance |
Managing Crontab
| Command | Effect |
|---------|--------|
| crontab -e | Edit crontab for current user |
| crontab -l | List current user's crontab |
| crontab -r | Remove all cron jobs |
| crontab -u alice -l | List Alice's crontab (root only) |
Practical Examples
Backup Script
# Create backup script
cat > /usr/local/bin/backup.sh << 'SCRIPT'
#!/bin/bash
tar -czf /backups/www-$(date +\%Y\%m\%d).tar.gz /var/www
# Keep only last 7 days
find /backups -name "www-*.tar.gz" -mtime +7 -delete
SCRIPT
# Make executable
chmod +x /usr/local/bin/backup.sh
# Add to crontab
crontab -e
# Add: 0 3 * * * /usr/local/bin/backup.sh
System Monitoring
# Check disk usage and alert
cat > /usr/local/bin/check-disk.sh << 'SCRIPT'
#!/bin/bash
THRESHOLD=90
USAGE=$(df / | awk 'NR==2 {print $5}' | sed 's/%//')
if [ "$USAGE" -gt "$THRESHOLD" ]; then
echo "Disk usage at ${USAGE}% on $(hostname)" | mail -s "Disk Alert" admin@example.com
fi
SCRIPT
chmod +x /usr/local/bin/check-disk.sh
# Every 30 minutes
crontab -e
# Add: */30 * * * * /usr/local/bin/check-disk.sh
Logging and Debugging
# Redirect output to log file
# In crontab:
*/10 * * * * /usr/local/bin/script.sh >> /var/log/script.log 2>&1
# Check cron logs (Ubuntu/Debian)
less /var/log/syslog | grep CRON
# Check cron logs (RHEL/CentOS)
less /var/log/cron
# Test command directly before scheduling
/usr/local/bin/script.sh
Environment Variables in Crontab
Cron runs with a minimal environment. Set variables inside crontab.
# Set environment variables in crontab
PATH=/usr/local/bin:/usr/bin:/bin
SHELL=/bin/bash
MAILTO=admin@example.com
HOME=/home/user
# Then schedule jobs
0 4 * * * /usr/local/bin/daily-report.sh
Summary
Crontab is the simplest, most universal task scheduler on Unix systems. Its five-field syntax controls minute, hour, day, month, and weekday with flexible patterns. Logging and environment configuration are essential for reliable automation.
Key takeaways:
- Crontab syntax: minute hour day month weekday |
- Use
*/Nfor every N minutes/hours | - Use
,for lists and-for ranges | - Keywords like
@dailysimplify common schedules | - Always redirect output:
>> /var/log/script.log 2>&1| - Set PATH and MAILTO in crontab for reliability |
- Test commands manually before scheduling |
- Check syslog to debug cron execution |
- Local crontab stops when computer sleeps |
What's Next: Cron-Job.Org
The next chapter covers cron-job.org, a free cloud cron service that runs your scripts even when your computer is off.