Cron is an Unix-like operating system software utility used to schedule automatic time-based commands. Entered commands can be in the form of Bash or Bash scripts that are meant to be automatically executed periodically at fixed times, dates or intervals.
Cron, also known as crontab (aka cron table) has a schedule formula for any minute of any day of the week, month and even any year in the future. It is perfect for scheduling repetitive commands (also known as Cron jobs, Cron entries or Cron tasks) or commands that should be executed at specific dates and times. Cron is often used for tasks like, log rotation, backup scripts, updating file indexes and running custom scripts.
All versions of Raspbian has the ability to use Cron. The reason for this post was created after realising the potential of a Raspberry Pi being a great, stand-alone device that can be used to montor and control and execute computer-related functions.
GUI-linux-based systems, e.g. Kodi’s Library Auto Update Add-on, might also use the cron schedule formula to run tasks. For these, the same principles as discussed in the Cron Table layout below can be used.
The command executed for a Cron job is a piece of shell code. Everything on Linux has a shell code or terminal command. It can be anything from running a simple Bash script, or a more complex one-line Linux command. Through some searching, even commands on the GUI can be converted to terminal commands. These commands can all be added to execute on (a) specific time/date(s) or even repetitively as Cron jobs.
Running as root, Crontab entries can also be used with
Creating a Crontab
One Cron table can contain many, if not all, Cron jobs in one. After creating a Cron table for the very first time, some systems will give the option to choose the default editor for editing the tables. I prefer to use
Creating a Crontab for root
Although each user on a Linux system has access to its own Crontab, e.g. on a Raspberry Pi, it often makes more sense to have one Crontab running from root. The root user has permission to run any command on any username. On Raspbian, Cron doesn’t require a user to be logged in to run the jobs.
To create, and later edit, a Cron table for the root user, simply use:
Creating a Crontab for a specific user
Each user on a specific Linux system has access to its own Crontab. Although not the norm, in some cases it might be necessary to have an user specific cron table. To, for example, create, and later edit, a cron table for the user ‘john’, use:
crontab -u john -e
The Cron table layout
# m h dom mon dow command
# * * * * * command to execute # ┬ ┬ ┬ ┬ ┬ # │ │ │ │ │ # │ │ │ │ │ # │ │ │ │ └─ day of week (0-7) (0-6 are Sunday to Saturday, or use names; 7 is Sunday, the same as 0) # │ │ │ └─── month (1-12) # │ │ └───── day of month (1-31) # │ └─────── hour (0-23) # └───────── min (0-59)
0 0 * * * bash /home/pi/backup.sh
would run the
backup.sh script every day at midnight, and
0,10,20,30,40,50 * * * * bash /home/pi/logging.sh
would run the
logging.sh script every 10 minutes.
To create cron entries without thinking too much, Generateit.net’s Cron Job Generator can also be used.
Using a test statement to control Cron commands
Because each command is basically a piece of shell code, a test statement can also be added to give additional control over when a command will be executed.
Test statements are for example like IF and conditional statements in Bash. As an example, a test statement would be needed to run a Cron job exactly every 2 days (some months for example have 31 days and the simple method [below] will not work):
0 7 */2 * * command
This will run the command on the 2nd, 4th, 6th, etc, day at 7AM/07:00, but if the month has 31 days, there will be a 3 days skip from the 30th until the 2nd day again.
By adding a test statement this can be fixed:
0 7 * * * [[ $((($(date +%s) / 86400 % 2)) == 0 ]] && command
Here the Cron job runs every day at 7AM/07:00, but it will only execute the command when
$((($(date +%s) / 86400) % 2)) == 0. The test statement makes sure it only runs exactly every 2 days (86 400 seconds).
Some tips & tricks
* * * * * command
will run the command every minute of every day.
*/10 * * * * command
will run every 10 (or N) minutes. Similarly
* * * */2 * command
will run the command every minute of every day every two (or N) months. Note that for days, it is every N days in a month. For months, it is every N months in a year.
will run once every time Cron, i.e. the system, boots up.
@reboot sleep 10 && command
will run once, 10 seconds after every reboot.
Many scripts will have an output. It can either be the intended output/standard message (stdout) or an error message (stderr). When an email service (e.g. SSMTP is activated, this stdout and stderr is what will be emailed to the indicated recipients.
By ‘piping’ messaged to
/dev/null, stdout will not be emailed. For example:
0 10 1 * * command > /dev/null
will run 10AM/10:00 every 1st day of every month. The intended output of the script will not be send to email (but errors will still be emailed).
Similarly, by adding
> /dev/null 2>&1 stderr and stdout will not be emailed.
0 8 * * 2 [ $(date +\%d) -le 07 ] && command
will run every Tusday at 8AM/08:00, but with the test statement the command will only trigger at 8AM/08:00 on the first Tuesday of the every month.
Making a backup of a Cron table
It is always a good idea to make regular backups of Cron tables.
crontab -l > /home/pi/crontab.bak
crontab -u pi -l > /home/pi/crontab-john.bak
will make a backup of a specific user Crontab (e.g. in the
Crontab backups can be retrieved by:
crontab -u pi /home/pi/crontab-john.bak
Using Cron with sSMTP
In the event a task generates an output message, Cron will automatically try to email the local administrator of the device. Output messages are either in the form of standard messages/intended output (stdout) or error messages (stderr). When an email server (e.g. by using sSMTP) is not defined, Cron will try to send an email to itself (generally not visible or noticeable). By using sSMTP, cron can be configured to use the correct email instead. Read more about using Cron and sSMTP together in Sending alert emails from a Raspberry Pi for home automation projects for more information…