crontab
(short for “cron table”) is a utility in Unix and Linux systems that allows users to schedule the execution of commands or scripts at specific times.
It is especially useful for performing repetitive tasks, such as running scripts, updating the system, or managing backups.
The cron
utility, which is the daemon that handles these scheduled tasks, uses configuration files called “cron tables” to determine which commands to run and when.
How Crontab Works
crontab
allows us to create and manage scheduled tasks through a series of configuration files. Each line in a crontab
file specifies a command to execute and a specific schedule for its execution.
The basic syntax of a line in crontab
is:
* * * * * /path/to/command
| | | | |
| | | | +---- Day of the week (0 - 7) (Sunday is 0 or 7)
| | | +------ Month (1 - 12)
| | +-------- Day of the month (1 - 31)
| +---------- Hour (0 - 23)
+------------ Minute (0 - 59)
How to Use Crontab on Raspberry Pi
First, we need to edit the crontab
file for your current user using the command:
crontab -e
This will open the crontab
file in the default text editor. If we don’t have one, it will ask us which one we want to use the first time.
Editing Another User’s Crontab
If you need to edit another user’s crontab
, use:
sudo crontab -u user -e
Where user
is the name of the user whose crontab
you want to edit.
Creating a New Scheduled Task
To add a scheduled task, simply add a line to specify a new scheduled task.
For example, to run a script called backup.sh
every day at 2:30 AM, we would add the following line:
30 2 * * * /home/pi/scripts/backup.sh
This line means:
- 30: Run at minute 30.
- 2: Run at 2 AM.
- *: Any day of the month.
- *: Any month.
- *: Any day of the week.
Finally, we save the changes and exit the editor. If you’re using nano
, you can do this by pressing Ctrl + X
, then Y
to confirm, and Enter
to save.
Running a Task at Startup
One of the most useful features of Cron is running a command or script when the system starts. For this, we use the special syntax @reboot
.
@reboot /path/to/command
Practical Examples
Here are some practical examples of scheduled tasks you can set up on your Raspberry Pi:
Run a Backup Script Weekly
To run a script called backup.sh
every Sunday at 3 AM:
0 3 * * 0 /home/pi/scripts/backup.sh
Synchronize System Time Every Hour
To synchronize the system time using ntpdate
every hour:
0 * * * * /usr/sbin/ntpdate pool.ntp.org
Clean Temporary Files Daily
To run a command that cleans temporary files every day at midnight:
0 0 * * * /usr/bin/find /home/pi/temp -type f -delete
Cron Logs
The cron
logs are usually found in /var/log/syslog
on Raspberry Pi OS. You can check these logs to verify if the scheduled tasks are running correctly:
grep CRON /var/log/syslog
Alternatively, for debugging issues, redirect the standard output and error of your commands to a log file:
30 2 * * * /home/pi/scripts/backup.sh >> /home/pi/logs/backup.log 2>&1