Level 1
0 / 100 XP

Automating Tasks with Cron Jobs

In this lesson, learn about Linux cron job and crontab. Cron jobs are a fundamental aspect of Linux that allow you to schedule scripts or commands to run automatically at specified times or intervals.

You will learn about the workings of cron jobs, their syntax, and practical applications. Specifically, you'll create a cron job to execute the backup script we created earlier every Sunday at midnight. Additionally, you will learn how to view cron logs, and log cron job output to a file.

Understanding Cron Jobs

Cron jobs are essential for automating repetitive tasks in a Linux environment. Each user on a Linux system can have their own crontab (cron table) to schedule tasks.

Cron Job Syntax

A cron job is defined by a line in a crontab, following this structure:

* * * * * /path/to/command

The five asterisks represent different units of time: minute, hour, day of the month, month, and day of the week, respectively. By replacing these asterisks with specific numbers or ranges, you can control when the cron job runs.

Creating a Weekly Backup Cron Job

Let's schedule your backup script to run every Sunday at midnight.

  1. Open the root users crontab file by prefixing your command with sudo:
sudo crontab -e
  1. Add the following line:
0 0 * * 0 /root/backup_script.sh

This tells cron to run /root/backup_script.sh at 00:00 (midnight) every Sunday.

  1. Save and exit the editor. Cron will update its schedule based on this.

Verifying Your Cron Job

To see your current cron jobs:

sudo crontab -l

Your backup script should be listed.

Logging Cron Job Output

To log the output of your cron job to a file:

  1. Modify the cron job line in your crontab:
0 0 * * 0 /root/backup_script.sh > /var/log/backup_script.log 2>&1

Here, > /path/to/logfile redirects standard output to a log file, and 2>&1 redirects stand…