Sunday, August 27, 2006

How to execute programs automatically in Linux

Have you found yourself doing something over and over? Wouldn't it be nice to do it all automatically? I mean, if you can have it done at exactly the time you want and without your intervention, it is great right?

Well this is possible and very easy. In this article you will learn how to do it and you will find out how easy it can be. To accomplish this we will be using cron and crontab.

Cron is a program that let's you execute a program, script, or command at any given time. To do this there is a file called crontab. Each user has his own crontab which he can edit and add any job he wants.

Now, how do I use cron? Well, there are a several ways you can do this. I'm going to show you the easiest one for me.

Commands

These are some commands you are going to need to use cron:

  • crontab -e
    This command is used to edit the crontab file which has all the information of the programs you want to run and when you want to run it. By typing this command the editor will appear and you will modify crontab however you want using some special syntax that I will show you after this section.

  • crontab -l
    This command displays the content of the crontab file. You can also make a copy of the crontab file if you use a redirect by doing 'cron -l > copy'.

  • crontab -r
    This command removes the content of the crontab file. You must be careful with this command for obvious reasons.

Syntax

Now that you know which commands to use with cron you will learn the syntax of the crontab file. If you execute 'cron -e' the editor will appear and you will have an empty file. Now, to add a job you have to follow some certain rules:

Minute Hour Day Month Day Command

  • Minute: This is the minute you want the command to be executed. For example to execute a command at 06:23 a.m. the Minute would be 23.

  • Hour: The hour you want the command to be executed. Following the example the hour would be 06.

  • Day: Now, this is the day of the month. If you wanted your command to be executed only the 15th, you would use 15.

  • Month: Used to specify what month you want the command to be executed.

  • Day: This is the day of the week. You can use: sun, mon, tue, etc.

  • Command: This is the command you want to execute. Remember you have to use the complete path of your program, script, etc. For example if you have a program on your home directory the command would be /home/user/program instead of just program.


Examples


Let's say you wanted to execute a command every sunday at 3:00 a.m. The syntax would be:

00 03 * * sun /home/user/program


To run it every night it would be:

00 03 * * * /home/user/program


I hope you enjoyed the tutorial and learned something. It's very easy as you can see. Also, keep visiting my blog because I will be writing a lot of tutorials.

Thanks for reading.