Ok so I have a cron that I need to run every 30 seconds.
Here is what I have:
*/30 * * * * /bin/bash -l -c \'cd /srv/last_song/releases/2012030813315
Cron job cannot be used to schedule a job in seconds interval. i.e You cannot schedule a cron job to run every 5 seconds. The alternative is to write a shell script that uses sleep 5
command in it.
Create a shell script every-5-seconds.sh using bash while loop as shown below.
$ cat every-5-seconds.sh
#!/bin/bash
while true
do
/home/ramesh/backup.sh
sleep 5
done
Now, execute this shell script in the background using nohup
as shown below. This will keep executing the script even after you logout from your session. This will execute your backup.sh shell script every 5 seconds.
$ nohup ./every-5-seconds.sh &
Use fcron (http://fcron.free.fr/) - gives you granularity in seconds and way better and more feature rich than cron (vixie-cron) and stable too. I used to make stupid things like having about 60 php scripts running on one machine in very stupid settings and it still did its job!
No need for two cron entries, you can put it into one with:
* * * * * /bin/bash -l -c "/path/to/executable; sleep 30 ; /path/to/executable"
so in your case:
* * * * * /bin/bash -l -c "cd /srv/last_song/releases/20120308133159 && script/rails runner -e production '\''Song.insert_latest'\'' ; sleep 30 ; cd /srv/last_song/releases/20120308133159 && script/rails runner -e production '\''Song.insert_latest'\''"
in dir /etc/cron.d/
new create a file excute_per_30s
* * * * * yourusername /bin/date >> /home/yourusername/temp/date.txt
* * * * * yourusername sleep 30; /bin/date >> /home/yourusername/temp/date.txt
will run cron every 30 seconds
Thanks for all the good answers. To make it simple I liked the mixed solution, with the control on crontab and the time division on the script. So this is what I did to run a script every 20 seconds (three times per minute). Crontab line:
* * * * 1-6 ./a/b/checkAgendaScript >> /home/a/b/cronlogs/checkAgenda.log
Script:
cd /home/a/b/checkAgenda
java -jar checkAgenda.jar
sleep 20
java -jar checkAgenda.jar
sleep 20
java -jar checkAgenda.jar
Currently i'm using the below method. Works with no issues.
* * * * * /bin/bash -c ' for i in {1..X}; do YOUR_COMMANDS ; sleep Y ; done '
If you want to run every N seconds then X will be 60/N and Y will be N.