Solved: How to schedule a cron job in Linux or Solaris

In this post we will see what’s a cron job and how we can set it.
Cron is managed by a crontab file. Its a configuration file in which we can schedule shell command to run periodically.
Scheduling cron
For modifying a cron you use a utility called crontab .
Before you can execute any crontab command you will have to set environment variables by executing below commands in your linux or unix command prompt.
TERM=vt100
EDITOR=vi
export TERM
export EDITOR
Now let’s see the different crontab commands.
Display current cron jobs
crontab -l
Edit cron file
crontab -e
Remove cron file (Be extremely careful with this command)
crontab -r
Cron format
You have to follow a specific format to schedule a cron job. See e.g. below:
30 22 * * 6 /home/cldvds/scripts/backup.sh
Let’s learn more about the asterisk (*) .
*       *        *        *         *        /file_execute.sh
–       –        –        –        –
|        |         |        |         |
|        |         |        |        +—– day of week (0 – 6) (Sunday=0)
|        |         |       +——- month (1 – 12)
|        |        +——— day of month (1 – 31)
|       +———– hour (0 – 23)
+————– min (0 – 59)
From the table above we can interpret that the  cron job will execute backup.sh file at 22:30 every saturday
Let’s take a few more examples
Execute every 5 mins
*/5 * * * *    /home/cldvds/scripts/backup.sh
Execute every hour
0 * * * *     /home/cldvds/scripts/backup.sh
Execute in every 3 hours
0 */3 * * *    /home/cldvds/scripts/backup.sh
Execute every Sunday at 1 am
0 1 * * 0    /home/cldvds/scripts/backup.sh
Tip:-
What if you want the cron to run at 22:30:30 i.e exact to seconds.
In such case at the start of your shell script put a sleep command as below
sleep 30
So, now the script will wait for 30 secs before executing.
Log redirection
30 22 * * 6 /home/cldvds/scripts/backup.sh >> /home/cldvds/scripts/logs.txt 2>&1
With the above command stderr (standard error) and stdout (standard output) will go to your logs.txt file.
Saving a cron file
Once you are done with cron schedule modification don’t forget to save the file.
You can save the file using standard save method of vi editor. The command sequence to save is  Esc :wq!

No comments:

Post a Comment