Cron Job

Cron usually be used to run a script in schedule.
for example if you want to backup a database in mysql using some language every Sunday, the cron will do it for you.

How to use it?
on the shell run:
#crontab -l
and this will list the cron jobs you have, if.

Now, the first thing is to create the script and check if it’s running right.
second if the script is bash, python, java, php, cgi or etc you need to add the reference to that command line
for example: in the head of your script file of java you should insert this line
#!/usr/bin/java
Note: To know where is the path of the command , run #which python or the command you want

After doing the script right and adding the command path, change the file permissions mode to be executable then add the script to the cron
#crontab -e
and here you edit the cron jobs.
Fields:
minute 0-59
hour 0-23
day 1-31
month 1-12
weekday 0-6

cron line description:
Cron Examples
About the script path:

This path can be run on the shell as it in the crontab, but where it’s output going to?
The output of the script will be sent as a mail for the cron owner. i.e: you will see a line in the shall telling you that you have mail. By typing #mail you will get it.
But what if you want the send the output to another place. You can redirect the output to log file for example.
example:
0 0 * * * /home/BackupDB.php >> /etc/httpd/logs/slog.log
this line means at mid night run the script and append the results to the log file

other examples:

*/4 * * * * /home/BackupDB.php >> /etc/httpd/logs/slog.log

this line means run it every 4 minutes.

0,15,30,45 * * * * /home/BackupDB.php >> /etc/httpd/logs/slog.log

this line means run it at 0, 15, 30 and 45 min of each hour

* 0-6 * * * /home/BackupDB.php >> /etc/httpd/logs/slog.log

means run it each minute from 00:00 till 06:00

Note: If the script is critical to run anytime, put the script where can’t be accessed by others. Like inside the root of php or tomcat.


About this entry