A Detailed Explanation of Cron Timers in Linux

When I first started working, there was a night when I stayed late to modify some code. I thought the new features were fine, so I submitted the changes and went home. The next morning, as soon as I arrived at my desk and before I even turned on my computer, QA came to find me. They said that the code I modified the night before had broken the regression tests. I thought I had completed a task ahead of schedule by working late, but instead, I had caused a problem. As a new employee, I was always a bit timid and clumsy. So, I worked hard to fix the issues and finally got the regression tests to pass. I was curious and asked QA why they were still working late to run tests when there was no rush to go live. They chuckled and explained that it was due to a cron job running automatically at scheduled times. While people can rest, machines cannot be idle.

It was from that moment that I learned about the magical tool called cron job. I then studied cron timers and have frequently used cron jobs in my subsequent work. Today, this article is a review of what I have learned about cron timers.

What is a cron timer?

The name “cron” comes from the Greek word “chronos,” which means “time.” In ancient Greek mythology, Chronos is the god of time, overseeing the passage of time. The cron timer in Linux, much like this god of time, can precisely control the execution time of tasks, automatically executing commands or scripts at specified times. It is an important tool for system management and automation. The cron timer first appeared in the 1970s for automatically executing periodic tasks, such as system maintenance, data backups, or sending emails regularly.

How does the cron timer work?

1. The crond daemon

In Unix systems, a daemon named “crond” runs in the background, responsible for periodically checking and executing scheduled tasks.

2. Cron expressions

This is the core configuration of a cron job, used to define the scheduling rules for task execution. It specifies the execution time of tasks in a specific format, including fields for minutes, hours, days, months, weekdays, and years, to indicate when tasks should be executed, such as every hour or at a specific time each day.

3. Crontab configuration file

The crontab stores configuration information for scheduled tasks, used to manage tasks that users need to execute periodically.

4. The workflow of the cron timer

      • First, the user needs to edit the crontab: crontab -e

      • For example: User cainiao writes a cron expression using the command crontab -e, such as: 0 2 * * * /usr/bin/backup.sh

      • Then save it to the crontab file: /var/spool/cron/crontabs/cainiao

      • The crond daemon checks the crontab file every minute. If a task reaches its execution time, it automatically runs the corresponding command. When the time reaches 2 AM, crond will execute the scheduled backup task configured by user cainiao: /usr/bin/backup.sh

Cron expressions

A cron expression is a string separated by 4 or 5 spaces,divided into 5 or 6 fields, each field represents a meaning. Cron has the following two syntax formats:

# Minute Hour Day Month Week {command to execute}    *   *    *   *   *   command

Or

# Minute Hour Day Month Week Year {command to execute}    *   *    *   *   *   *   command

Explanation of each field

Field Value Range Description
Minute 0 ~ 59 Which minute of the hour to execute
Hour 0 ~ 23 24-hour format, 0 represents midnight
Day 1 ~ 31 Which day of the month
Month 1 ~ 12 1 = January, 12 = December
Week 0 ~ 6 0 and 7 both represent Sunday, 1-6 represent Monday to Saturday
Year (optional) Leave empty, 1970~2099 Usually, the year does not need to be specified, only 5 fields

Each field’s value may include some special symbols, as explained below:

* represents all possible values , represents multiple values (e.g., 1,3,5)

represents a range (e.g., 1-5 means from 1 to 5)

/ represents intervals (e.g., */2 means every 2 units)

? is used only in the day and week fields, indicating unspecified

Common examples of cron expressions

# Execute every minute * * * * * command
# Execute at the 30th minute of every hour 30 * * * * command
# Execute at 2 AM every day 0 2 * * * command
# Execute at 3 AM every Sunday 0 3 * * 0 command
# Execute at 4 AM on the 1st of every month 0 4 1 * * command
# Execute at 9 AM on weekdays (Monday to Friday) 0 9 * * 1-5 command
# Execute every 2 hours 0 */2 * * * command
# Execute every 2 hours from 8 AM to 6 PM every day 0 8-18/2 * * * command
# Execute at 1 AM every Saturday 0 0 1 ? * SAT
# Execute at 10:15 AM on the last day of the month 0 15 10 L * ?

Crontab file

The crontab file specifies the tasks to be executed. In Linux, task scheduling is divided into two categories:system-level scheduled tasksand user tasks.

Generally, system-level scheduled tasks are periodic tasks that the system needs to perform, such as writing cached data to disk, log cleaning, etc. System-level scheduled tasks are usually configured in the following locations:

/etc/crontab              # Main system configuration file
/etc/cron.d/              # System scheduled tasks directory
/etc/cron.daily/          # Scripts executed daily
/etc/cron.hourly/         # Scripts executed hourly
/etc/cron.weekly/         # Scripts executed weekly
/etc/cron.monthly/        # Scripts executed monthly

System crontab format (6 fields)

Minute  Hour Day Month Week User Command 0    2    *   *   *  root /usr/bin/backup.sh

Linux is a multi-user system. User-level tasks are periodic tasks that users need to perform, such as user data backups, scheduled email reminders, etc. Users can use the crontab tool to customize their scheduled tasks. All user-defined crontab files are stored in the /var/spool/cron directory. The filenames correspond to the usernames, and the permission files are as follows:

/etc/cron.deny     # Users listed in this file are not allowed to use the crontab command
/etc/cron.allow    # Users listed in this file are allowed to use the crontab command
/var/spool/cron/   # Directory where all user crontab files are stored, named after the username

User crontab operations

# Edit the current user's crontab crontab -e
# View the current user's crontab crontab -l
# Delete the current user's crontab crontab -r
# Edit a specified user's crontab (requires root privileges) crontab -u username -e

Features of cron timers

1. Simple and easy to use

The configuration format of cron is very intuitive and easy to use. For example:

# Backup data at 2 AM every day0 2 * * * /usr/bin/backup.sh

With just a simple line of configuration, you can achieve daily repetitive tasks. This simplicity is one of the greatest charms of cron.

2. Minimal resource usage

Cron is like a “minimalist”; typically, the crond process only uses a few MB of memory, and the CPU usage is close to 0%. It spends most of its time sleeping and only wakes up to check tasks.

3. High reliability

After more than 50 years of testing, the stability of cron has reached industrial-grade standards. It has strong fault tolerance; even if a task fails, it does not affect other tasks. All execution statuses are logged, and most importantly, it can automatically resume operation after a system reboot without manual intervention.

4. Compatibility

From ancient Unix systems to the latest Linux distributions, from servers to embedded devices, cron is almost everywhere. This widespread compatibility makes it widely used.

Practical application scenarios of cron timers

1. System maintenance tasks

# Clean temporary files at 2 AM every day0 2 * * * find /tmp -type f -mtime +7 -delete
# Clean log files at 3 AM every Sunday0 3 * * 0 find /var/log -name "*.log" -mtime +30 -delete
# Automatically restart service at 5 PM every Friday0 17 * * 5 systemctl restart myservice
# Check disk space every hour0 * * * * df -h | mail -s "Disk Usage Report" [email protected]
# Update system packages at 3 AM every day0 3 * * * apt update && apt upgrade -y >> /var/log/system_update.log 2>&1
# Clean website access logs weekly0 2 * * 0 find /var/log/nginx -name "*.log" -mtime +7 -delete

2. Data backups

# Backup database at 1 AM every day0 1 * * * mysqldump -u backup_user -p'password' mydb > /backup/mydb_$(date +\%Y\%m\%d).sql
# Perform a full system backup weekly0 2 * * 0 rsync -av /home/ /backup/home_backup/
# Backup configuration files on the 1st of every month at 3 AM0 3 1 * * tar -czf /backup/config_$(date +\%Y\%m).tar.gz /etc/
# Perform a full backup and upload to the cloud at 4 AM every Sunday0 4 * * 0 tar -czf /backup/full_backup_$(date +\%Y\%m\%d).tar.gz /var/www /etc && aws s3 cp /backup/full_backup_$(date +\%Y\%m\%d).tar.gz s3://company-backup/

3. Monitoring and alerting

# Check service status every 5 minutes*/5 * * * * systemctl is-active nginx || echo "Nginx is down" | mail -s "Alert" [email protected]
# Check memory usage every hour0 * * * * free | awk 'NR==2{printf "Memory Usage: %s/%sMB (%.2f%%)\n", $3,$2,$3*100/$2 }' > /var/log/memory_usage.log
# Count website visits every hour0 * * * * awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -nr > /var/log/hourly_visits_$(date +\%Y\%m\%d\%H).log
# Send daily report reminder at 9 AM on weekdays0 9 * * 1-5 echo "Don't forget to submit your daily report" | mail -s "Daily Report Reminder" [email protected]
# Check for abnormal logins weekly0 8 * * 1 grep  "Failed password"  /var/log/auth.log | tail -20 | mail -s "Weekly Security Report" [email protected]

Some practical tips for cron timers

1. Set environment variables completely

# Set environment variables at the beginning of the crontab fileSHELL=/bin/bashPATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/[email protected]
# Then define the task0 2 * * * /home/user/backup.sh

2. Use absolute paths for scripts and ensure correct permissions

# Use absolute paths0 2 * * * /usr/bin/python3 /home/user/script.py
# Ensure the script is executablechmod +x /home/user/script.py

3. Logging

# Redirect output to a log file0 2 * * * /home/user/backup.sh >> /var/log/backup.log 2>&1
# Log only errors0 2 * * * /home/user/backup.sh 2>> /var/log/backup_error.log
# Silent execution0 2 * * * /home/user/backup.sh > /dev/null 2>&1

4. Debugging and testing

When testing new tasks, set them to execute every minute:# Testing phase: execute every minute* * * * * echo "Test at $(date)" >> /tmp/cron_test.log# Confirm normal operation before changing to actual time0 2 * * * /usr/bin/real_task.sh

5. Ensure crond is in service status before task execution

# Check crond service statussystemctl status cron
# Or service cron status
# Start crond servicesystemctl start cron

Cron is a fundamental tool for Linux system management, mastering it can greatly improve work efficiency. Although modern alternatives like systemd timers exist, cron remains the most commonly used scheduled task tool due to its simplicity, reliability, and effectiveness. Thank you for reading this far. If this article has been helpful to you, feel free to follow, like, and share. If you have any questions about cron, please leave a comment for discussion. Finally, here is an article on systemd timers in Linux for your reference.

A Detailed Explanation of Timers in Linux Systemd

A Detailed Explanation of Cron Timers in Linux

Leave a Comment