Using Cron for scheduling tasks

Using Cron for scheduling tasks
Published: by Renier Delport
Last updated: 11 July 2017
Credits: Featured image from Brightwallpapers.com

Cron is a software utility used to schedule automatic time-based commands or shell scripts on Linux and other Unix-like operating systems. Schedules are manually inserted to automatically run these tasks 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 tasks (or ‘jobs’) on for example the Raspberry Pi running Raspbian. This post will go through the basics and some tips on how to use Cron’s functionality.

The commands

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

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. Most new users will use nano.

Creating a Crontab for root

Although each user on a specific Linux system has access to its own Crontab, on, for example, 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:

crontab -e

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 ‘pi’, use:

crontab -u pi -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 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.

@reboot command

will run once every time Cron “boots up”.

@reboot sleep 10 && command

will run once, 10 seconds after every reboots.

Many scripts will have an output. It can either be the intended output (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 adding /dev/null to the end of an entry, stdout will not be emailed. Fore 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.

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

or

crontab -u pi -l > /home/pi/crontab-pi.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-pi.bak

More website development related posts

Fiverr – Freelance services marketplace for the lean entrepreneur
Fiverr is the world’s largest freelance services marketplace for entrepreneurs to focus on growth & create a successful business at affordable costs.
[date format="j F Y"] | 2 837 reader(s) found this helpful so far.
A better way to add fonts to a WordPress site
A better way to add fonts to a WordPress site
See a better way to add fonts to a #WordPress site...
16 September 2017 | | 1 reader(s) found this helpful so far.
WordPress code snippets
WordPress: Display categories without the link
See #howto display categories without the link in #WordPress... #WPcode
11 September 2017 | | 0 reader(s) found this helpful so far.
Working with custom image sizes in WordPress
Working with custom image sizes in WordPress
See #howto work with custom image sizes in #WordPress...
7 August 2017 | Updated 19 September 2017 | | 1 reader(s) found this helpful so far.
WPtouch mobile theme
Make your website mobile friendly with WPtouch – easily, simply & elegantly
See #howto make your website mobile friendly with #WPtouch...
19 March 2016 | Updated 2 September 2017 | | 3 reader(s) found this helpful so far.
Using MailChimp to Send Automatic Post Notifications
Using MailChimp to send automatic post notifications
See #howto use #MailChimp to send automatic post notifications...
5 March 2016 | | 4 reader(s) found this helpful so far.

Did you like this post?

(5 reader(s) found this helpful)
You have not rated this post yet. You can do so clicking on the thumbs up icon.
Loading...

Please share, comment & Disqus

Please use the buttons on the left or the bottom of the screen to share this post.

Your comment is important to us, but please keep the comments constructive and polite.

Comment via Facebook

Disqus

About the author
Renier finds himself busy with creative web design and his websites, motorcycling, photoshopping, micro electronics, non-commercialised music, superhero movies, badass series and many other things that are not interesting to most people.