Table of Contents
In Unix and Unix-like operating systems, the cron command allows for the scheduling of commands, meaning their registration in the system so they can be executed periodically and automatically by the system itself.
To achieve this, a daemon called crond is used. This daemon constantly runs in the background and, once per minute, reads the contents of the scheduled command registry (crontab) and executes those commands whose waiting period has expired. A command executed from crontab is called a cronjob.
Crontab Structure
Every user on a Unix/Linux system can create and manage their own crontab file, which lists all the cronjobs of that user. To modify the crontab, use the command:
1 2 |
crontab -e |
To display existing cronjobs:
1 2 |
crontab -l |
To remove all cronjobs for the current user:
1 2 |
crontab -r |
Syntax
The syntax of a cron command is divided into two subgroups:
- A sequence of five fields representing:
- Minutes (0-59)
- Hours (0-23)
- Day of the month (1-31)
- Month (1-12)
- Day of the week (0-6, where 0 corresponds to Sunday)
- The command to execute, which is entered in the same way as it would be in a terminal.
For example:
1 2 |
30 2 * * 1 /home/user/script.sh |
This cronjob will execute the script script.sh
every Monday at 2:30 AM.
A useful method for testing and verifying syntax is using the website Crontab Guru, which offers an intuitive interface for interpreting and generating cron expressions.
Common CronJob Examples
Here are some common configurations:
- Execute every minute:
12* * * * * /home/user/script.sh - Execute every hour:
120 * * * * /home/user/script.sh - Execute every day at 3:00 AM:
120 3 * * * /home/user/script.sh - Execute on the first day of each month at 12:00 PM:
120 12 1 * * /home/user/script.sh - Execute every Sunday at 10:00 PM:
120 22 * * 0 /home/user/script.sh
Debugging and Logs for CronJobs
To verify if a cronjob has been executed correctly, you can check the system logs:
1 2 |
cat /var/log/syslog | grep CRON |
Or, to check errors specific to a user's cronjobs:
1 2 |
grep CRON /var/log/syslog | grep "username" |
If a cronjob is not executing as expected, ensure that:
- Check the file permissions of the script to be executed (
chmod +x script.sh
). - Use the absolute path in commands (
/usr/bin/python3 /home/user/script.py
instead ofpython3 script.py
). - Redirect output to a file to check for possible errors:
12* * * * * /home/user/script.sh >> /home/user/cron.log 2>&1
Conclusion
The cron command is an essential tool for automating operations on Unix/Linux systems. With proper configuration and a good understanding of its syntax, you can efficiently manage the periodic execution of commands and scripts, optimizing server administration and maintenance processes.