Thursday, June 2, 2011

Adding cron job to ubuntu

Many times we need to add cron jobs to perform many back end tasks. Like sending mails with database dump as an attachment. So the following section will guide you to create a shell script and then adding it as a cron job.

For this you should have little bit knowledge about the shell script and unix processes. I will make you learn by demonstrating you to send database backup log.

For this you require 'mutt', a unix based email client. If you don't have this utility then install it using the following comamnd:

 sudo apt-get install mutt

Now we will start writing the shell script. Please find the following demo code:


#!/bin/sh
dir_path=/home/test/cron_script
#change the dircetory to desired location defined in dir_path
cd "$dir_path"

#create a variable for the filename appended with date of backup
file_name=backup_$(date +%Y-%m-%0e).sql

#create a variable for the zip filename
zip_file_name="$file_name.zip"
#take the backup of the specified database and redirected the output to the already defined file_name
mysqldump -u user --password=password test_database > "$file_name"

#zip the file
zip "$zip_file_name" "$file_name"


#send the mail with the database backup and biller log
echo | mutt -s 'daily backup of database' -a "$dir_path/$zip_file_name" -- admin@example.com
 
echo "Mail sent"

#remove all the above created files
rm $dir_path/backup*

Copy the above mentioned code and paste it in a file having name like cron_script.sh. Make sure to modify the script as per your file location and email address.

Add execute permission to the above mentioned file. For example:

sudo chmod 776 cron_script.sh

After adding  execute permission test the script by running it manually. Like

./cron_script.sh 

and check the output if every thing goes fine then you will find "Mail sent' text at the console, and in your mails also.

Now add the shell script in the crontab. Crontab is a file which maintains all the information about the schedule of each backend process. All the current cron jobs can be listed by the following command:

crontab -l


Now open the crontab file using the following command :

sudo crontab -e

and the new job as:

0 15 * * * /path_to_the_script_file/cron_script.sh

Please find more information on the following link about crontab:

http://en.wikipedia.org/wiki/Cron

Bydefault the cron configuration is per day. This can be changed as per our need. Now wait for next day to find the result of the whole effort that you have added.

Best of Luck!!!