Using Cron to automate tasks

When using Linux or even Unix systems there are at times certain tasks that you may want to be started at a specific time or date, some of those you may want to be repeated some you may not. Luckily there is something that can assist you with this, it is called Cron. While now there are several implementations of cron they all work in similar ways so what is shown below should work on all of them.

Cron uses a file called the crontab this file is where all of the tasks are stored these tasks could be executing a script or just running a command such as a wget download a file but they are all stored in the same place. To access the crontab you use the crontab application, to do this you use the commands below.

To view the crontab

crontab -l

To edit the crontab

crontab -e

To remove the crontab

crontab -r

The above three commands should get you started but there are more available for more advanced functions.

Before you start adding to the crontab you need to understand how to set the time and date for the command to start. The time and date is placed before the command you want to use and is set out like below.

minute hour day-of-the-month month day-of-the-week

Below are the values you can use

minute: 0 – 59

hour: 0 – 23

day-of-the-month: 1 – 31

month: 1 – 12

day-of-the-week: 0 – 6 (0 = Sunday and 6 = Saturday. You can also use 7 to represent Sunday)

you can also use * to represent all and you can have ranges such as 1-5 for the day of the week if you only want the commands to run on weekdays and not the weekend. Also to get something to run say every 10 minutes you could put */10 in the minute section.

This should give you enough to start using cron but I will give a few examples to help you understand how it works, also if you are used to 12 hour clocks you may want to learn how 24 hour time works as that is what cron uses.

The task below will cause a script to be run called alert.sh at the beginning of every month at 8:30 am.

30 8 1 * * /home/someuser/scripts/alert.sh

The next example is for a wget download that runs every weekend (both Saturday and Sunday)  at midnight.

0 0 * * 6-7 wget http://www.example.com/download/file.jpg

Now it is up to you to apply what was said above to the tasks that you have that need to be run periodically. But with that said don’t get carried away automating stuff as some things can not be automated safely and may result in unintended side effects.

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s