Tuesday 1 July 2014

How to run a Linux script every few seconds under cron - EXPLAINDED and SOLVED!

Crontab is a scheduler for Linux that run scripts on certain time of day, week or month!

It has 5 fields for setting that!

_  _  _  _  _  script.sh

First field is for minutes.(00-59)
Second field is for hours.(00-23)
Third field is for day in a month(1-31)
Forth field is for month in a year (1-12)
Fifth field is for day in a week (0-6, where 0 is sunday)

If you have star(it is joker sigh after all) is some field that means that all numbers is included!
So

* * * * * script.sh

means that script.sh will execute every minute, every hour, every day in a month, every day in a week and every month in a year.
 
Minimum time resolution that you can use for cron is one minute!  Script will be executed in 00 seconds on particular time. But what if you had do execute your script on 20th second of every minute or every 20 seconds?
From cron you cannot resolve this, because as we said - minimum time resolution is one minute. (Resolution is smallest step between two neighbour points)

In case that you that "/number of seconds" will resolve your issue, you are wrong. This / does not mean divide like in math. It means repeat every number of minutes, hours,etc. depending in what field it is standing.

If you have something like this

*/5 * * * * script.sh

this will execute script.sh every 5 minutes.

or

* */5 * * * script.sh

will execute script every 5 hours!
You get the point!

Ok, are problem needs different approach!

If you want script.sh to be executed every 15 seconds, do following thing!

server#cp script.sh script15.sh
server#cp script.sh script30.sh
server#cp script.sh script45.sh 

In script15.sh enter following line

#!/bin/bash
sleep 15
.
.
 

before commands in script!
For script30.sh enter sleep 30, for script 45.sh enter sleep 45.
Sleep command delay everything for certain amount of time in seconds!

sleep - delay for a specified amount of time

Now in crontab

* * * * * script.sh
* * * * * script15.sh
* * * * * script30.sh
* * * * * script45.sh
So, all scripts will be executed in same time but because of sleep command inside of then they will be delayed for specific amount of seconds!




No comments: