como-usar-crontab-en-raspberry-pi

What is Crontab and How to Use it on Raspberry Pi

  • 3 min

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 of 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, the first time it will ask us which one we want to use.

Create a New Scheduled Task

To add a scheduled task, we simply need to 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, save the changes and exit the editor. If you are using nano, you can do this by pressing Ctrl + X, then Y to confirm, and Enter to save.

Run a Task at Startup

One of the most useful functions of Cron is to run 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 configure on your Raspberry Pi:

Cron Logs

cron logs are usually found in /var/log/syslog on Raspberry Pi OS. You can check these logs to verify if scheduled tasks are running correctly:

grep CRON /var/log/syslog

Alternatively, to debug 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