Cron to Automate Tasks

Install Cron

sudo apt update

sudo apt install cron

You’ll need to make sure that cron will run in the background too:

sudo systemctl enable cron

Cron jobs are recorded and managed in a particular file known as crontab. Each user profile on the system can have its crontab where they can schedule jobs, which is stored under /var/spool/cron/crontabs/

To schedule a job, open your crontab for editing and add a task written as a cron expression.

minute hour day_of_month month day_of_week command_to_run

*: In cron expressions, an asterisk is a wildcard variable representing “all.”

Referring to a previous post (VirtualBox Virtual Machine Backup on Ubuntu Server Host), I’m going to list the three lines to automate the backup.

0 22 * * * /path/to/vm-stop.sh >/dev/null 2>&1
0 0 * * * /path/to/vm-export.sh >/dev/null 2>&1
0 2 * * * /path/to/vm-start.sh >/dev/null 2>&1

>/dev/null 2>&1: It means that stderr (2 – containing error messages from the executed command or script) is redirected (>&) to stdout (1 – the output of the command) and that the latter is being redirected to /dev/null (the null device). This way, you can suppress all messages issued by the executed command. In cron, this is often done to avoid being spammed by lots of irrelevant messages from service scripts.

Those expressions should be put in a crontab. A crontab is a particular file that holds the schedule of jobs cron will run. However, these are not intended to be edited directly. Instead, it’s recommended that you use the crontab command.

crontab -e

When you save the file is stored in the folder /var/spool/cron/crontabs/, so save it without changing the default path in the editor.

If you’d like to view the contents of your crontab, but not edit it, you can use the following command:

crontab -l

You can erase your crontab with the following command:

crontab -r