Using Cron to automate tasks on a Linux VPS

Using Cron to automate tasks on a Linux VPS

The most common way to automate tasks in Linux is through cron jobs. By doing so, you will let the tasks run in the background while you carry on your work, without worrying about manual initialization of any of those tasks.

Cron itself is a daemon, or a program running in the background. Cron jobs come in handy for scheduling tasks on a VPS and automating a large variety of maintenance-related jobs. The schedule that you establish for these automated tasks is called crontab.

On Linux machines, almost all distributions comes with cron installed by default. If that is not the case, then go ahead and enter these commands:


For Ubuntu/Debian:

sudo apt-get update
sudo apt-get install cron

For Cent OS/Red Hat Linux:

sudo yum update
sudo yum install vixie-cron crontabs

And to make sure it runs in the background, type in:

sudo /sbin/chkconfig crond on
sudo /sbin/service crond start

Understanding the syntax

To be able to schedule tasks properly, you must first understand the syntax. Every command is broken down into schedule and command, for example:

 5 * * * * curl

These are a few essential shortcuts for the equivalent numeric schedule:

@hourly - Shorthand for 0 * * * *

@daily - Shorthand for 0 0 * * *

@weekly - Shorthand for 0 0 * * 0

@monthly - Shorthand for 0 0 1 * *

@yearly - Shorthand for 0 0 1 1 *


Once you’ve decided on a schedule and a task you’d like to automate, you must select a location to save it to so that the daemon can easily find it. Most likely, that location is the crontab. The files for each user reside at /var/spool/cron/crontab, and they can be accessed and edited through the crontab command:

crontab -e

This will open a text editor where you can input your schedule with each job on a new line. You can also erase your crontab with this command:

crontab -r


As each cron job is executed, the email address associated that user will get emailed the output unless it is redirected into a log file or into /dev/null. This email address can be manually specified or changed through a  “MAILTO” setting at the top of the crontab. Additionally, you can specify the shell you’d like to run, the path where to search for the cron binary and the home directory, like so:

crontab -e

MAILTO=”[email protected]
#This is a comment
* * * * * echo ‘Run this command every minute’

Similarly, if you want to append to a log file, it’s as simple as:

* * * * * echo ‘Run this command every minute’ >> file.log

Or if you wish to pipe into an empty location, use /dev/null:

* * * * * /usr/bin/php /var/www/ > /dev/null 2>&1

And you’re done automating your tasks using Cron on Linux VPS!


Leave a Reply

Your email address will not be published. Required fields are marked *