5 Crontab Examples to Help You Automate Linux Tasks

The cron program automates the execution of other programs on Linux. Cron is a daemon that runs continuously and starts other programs according to a given schedule. Several different files define this schedule. They are individually known as crontabs.

Cron can schedule any Unix command or task. Sometimes, you’ll want to work with a simple command. Other times, you’ll need to write a script to carry out the full task. Cron works fine with either approach. It also supports complicated scheduling rules and flexible ways of dealing with the script output.

Whether you’re carrying out simple user tasks or full-blown system administration, understanding how cron works using practical examples is a must.

1. Cleaning Up /tmp Using a System-Wide Crontab

The /tmp directory is a temporary location for general-purpose use by any program or user of the system. Many Unix systems will delete old files in the /tmp directory during startup. Others schedule this operation, quite often using cron.

However, if you want custom control over this process, or want to apply it to a different directory, setting up a quick cron task is an easy way to do so.

Here’s one way of cleaning up /tmp, or any other directory of your choice:

1 3 * * * /usr/bin/find /tmp -type f -atime +10 -delete

At one minute past three, every day, cron will execute this command. It uses the find command to search for files in the /tmp directory. It filters out anything but normal files that were last modified at least 10 days ago. It then removes all such files that it finds.

You should add a command like this to a global crontab such as /etc/crontab or root’s crontab using sudo crontab -e. The command needs to run as root so it can delete files in /tmp regardless of who owns them.

Note that this example specifies the full path to the find command. Cron uses a basic PATH setting to search for executables, so if the command is in a standard place (like /usr/bin), this isn’t really necessary. You can specify an alternative PATH in the crontab itself if you prefer that approach. But using a full path for commands is a little bit more resilient.

If you’re working on a project that writes logs or stores cached data, this kind of approach can be vital if you’re deleting files to clear disk space. While the above example is a quick-and-dirty approach, you should use a command such as tmpwatch, if it’s available.

2. Database Backups Twice Daily

From now on, let’s focus on user-specific tasks that you can manage via your local crontab. You can edit your current user’s crontab using the following command:

crontab -e

This crontab should contain tasks that are specific to your user account. Imagine you’re working on a project involving populating a MySQL database. You can use the mysqldump tool to create an SQL dump of an entire database. By redirecting its output, you can have easy, scheduled database backups.

30 4 * * * /usr/local/mysql/bin/mysqldump --login-path=local --databases albums > /tmp/album-db.$(date +%s).sql

By default, cron sends output (including errors) via email to the user the crontab file belongs to. But you can redirect output in the same way you would from a command line, using the > filename notation.

Note how the above example uses command substitution to build the filename based on the current Unix timestamp. Because the % symbol has a special meaning to cron, the command needs to escape it with a preceding backslash.

3. Checking Site Uptime With a Custom Script

You might have noticed that the command in the last example was uncomfortably long. Thankfully, there’s nothing to stop you from saving commands in a script and executing that script via your crontab. Here’s an example that runs a script every minute:

* * * * * /Users/bobby/bin/site-monitor.sh

Note that, in theory, you can use the HOME variable or tilde expansion for a shorter command:

* * * * * ~/bin/site-monitor.sh

You might choose to avoid doing so, in case cron ever stops supporting it. There’s no real harm in using the full path and it’s arguably more readable.

The script itself uses the curl program to fetch the HTTP status code for a given URL. If the status indicates anything other than success, the script writes a message to the output.

As mentioned previously, cron will send this output to us via email. It can be useful to have commands in cron produce no output on success.

#!/bin/bash
STATUS=`curl -s -o /dev/null -I -w "%{http_code}" http://example.com/`
if [ "$STATUS" != "200" ]
then
echo "site appears to be down"
fi

4. Disk Space Reports via Email

If you want to alter cron’s default emailing behavior, you can use the MAILTO environment variable. Cron supports a few variables which you can set in your crontab file. Cron then applies these variables to the environment of each command that follows.

To set an alternative target email address, use the following format:

MAILTO=user@example.com

You’ll need to run this on a machine that’s set up to send an external email if required. Here’s an example that will send an email to another user on the same machine. It runs twice a day, at 12:00 and 23:00. The df command displays free disk space, so this crontab entry delegates the task of checking that disk space looks OK:

MAILTO="sarah"
0 12,23 * * * /bin/df -h

The resulting email will look something like this:

Note that cron adds its own custom email headers. These can be useful for debugging. You can also disable cron’s default emailing behavior using an empty string:

MAILTO=""

5. Broadcast a Message at Specific Times

The other examples use fairly straightforward scheduling, but cron supports a powerful syntax for time specifications. It handles not just exact matches, but also:

  • Multiple values separated by comma (,)
  • Ranges specified with a hyphen ()
  • Step values after a forward slash (/)

So, for example, if you want to send a message to all logged-in users, twice an hour during working hours, but only every three hours, something like the following will suffice:

0 15,45 9-17/3 ? * * * echo 'Enjoy your work!' | wall

This command will execute at 15 and 45 minutes past the hour, every three hours during the hours of 9 am to 5 pm. The wall command sends a message to each logged-in terminal user.

You might even find that cron offers more flexible scheduling than your calendar app. Some variations allow you to specify commands to execute on the second Friday of a month or on the closest weekday to a certain date.

Cron Can Automate Many Types of Linux Tasks

This is a small selection of the kind of tasks that cron can help you automate. It might take some time to get comfortable with the complex syntax, but cron is a powerful utility. You can use cron for both system-wide tasks and user-specific ones.

With a complicated syntax for scheduling, cron is powerful, but you should probably have a good reference to hand. Crontabs allow comments, so you might want to include a comment line in yours to document the time fields.

Source: makeuseof.com

Related posts

9 Lightroom Mobile Tips and Tricks You Should Be Using

8 Techniques I Use to Capture Stunning Panorama Photos on My Smartphone

I Tried Window Tiling in macOS Sequoia and Its a Game-Changer