Using Cron for scheduling tasks

Using Cron to schedule tasks on the Raspberry Pi
Published: by
Last updated:
Categories
Raspbian

Cron is a Unix-like operating system software utility used to schedule automatic time-based computer commands. The Raspberry Pi can also use Cron.

Introduction to Cron on the Raspberry Pi

Cron, also known as Crontab (aka cron table) has a scheduling formula for any minute of any day of the week, month and 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. 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.

All versions of Raspbian have the ability to use Cron. Raspbian on a Raspberry Pi is also a great stand-alone device that can be used to monitor, control and execute computer-related functions.

Other GUI-Linux-based systems, e.g. Kodi’s Library Auto Update Add-on, also uses the cron schedule formula to run tasks. For these, the same principles discussed here will apply.

The commands

The command executed for a Cron job is a piece of shellcode. Everything on Linux has a shellcode or terminal command. It can be anything from running a simple Bash script, or any one-line Linux command. Python scripts can also be used.

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 sudo.

Creating a Crontab

One Cron table can contain one or many, Cron jobs. 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. For this post, it is recommended to use nano to create a Crontab.

Creating a Crontab for root

Although each user on a Linux system has access to its own Crontab, it often makes more sense to have one Crontab running from root — e.g. when using a Raspberry Pi.

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, the crontab command can be used:

crontab -e

Creating a Crontab for a specific user

As mentioned above, 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 a 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)

Simple examples

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 shellcode, a test statement can also be added to give additional control over when a command will be executed.

Test statements are for example 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 7 AM/07:00, but if the month has 31 days, there will be a 3 day 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 7 AM/07:00, but it will only execute the command when $((($(date +%s) / 86400) % 2)) == 0. The test statement ensures that it only runs every 2 days (i.e. every 86 400 seconds).

Using Cron with sSMTP

In the event that a task/script 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 an email server, Cron can be configured to use the correct email instead.

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.

Running a Cron command at bootup/reboot

@reboot command

will run once every time Cron, i.e. the system, boots up.

Running a Cron after bootup/reboot

@reboot sleep 10 && command

will run once, 10 seconds after every reboot.

Script outputs (stdout and stderr)

In the case where a script has an output, it will be piped to output/standard message (stdout) or as an error message (stderr).

When an email service (e.g. SSMTP) is activated, this stdout and stderr are what will be emailed to the indicated recipients.

By ‘piping’ messages to /dev/null, stdout will not be emailed. For example:

0 10 1 * * command > /dev/null

will run 10 AM/10:00 every 1st day of every month. The intended output of the script will not be sent to email (but errors will still be emailed).

Similarly, adding > /dev/null 2>&1 stderr and stdout will not be emailed.

Running a Cron command on the first day of the month

0 8 * * 2 [ $(date +\%d) -le 07 ] && command

will run every Tuesday at 8 AM/08:00, but with the test statement, the command will only trigger at 8 AM/08:00 on the first Tuesday of 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

or

crontab -u pi -l > /home/pi/crontab-john.bak

will make a backup of a specific user Crontab (e.g. in the /home/pi directory).

Crontab backups can be retrieved by:

crontab /home/pi/crontab.bak

or

crontab -u pi /home/pi/crontab-john.bak

Conclusion

Cron is a great way to schedule repetitive commands or commands that should execute at specific times, days, weeks, months or even years. Together with the Raspberry Pi, Cron can be used as an automation device.

About the author
Renier busies himself with improving his English writing, creative web design and his websites, photoshopping, micro-electronics, multiple genres of music, superhero movies and badass series.
Behind the Scenes is a free, informative website. If you find value in any of our content, please consider making a donation to our cause, or becoming a Patron for exclusive content.
Donate via PayPal Become a Patron

Save, share & discuss

Your comment is important, but don't be a knob. Keep it constructive and polite.

Leave a Reply

Your email address will not be published.

More Raspbian related posts