Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cron jobs -- to run every 5 seconds

Tags:

bash

cron

I want to create cron job that runs a script every 5 seconds. Seeing that cron jobs only allows increments of minutes 0-59 and so on.

I thought to create another script that calls my original script written below.

#!/bin/bash

while true
do
# script in the same directory as this script. is this correct?
bash makemehappy.sh
sleep 1
done

I now, need to know how to run this script every time i boot my computer and for it to start itself if it isn't running for some reason.

I am also aware that running this script every minute wouldn't be a good thing. :)

if there is an easier way to run a script every 5 seconds please advise.

Please and thank you.

like image 788
myusuf3 Avatar asked Jul 26 '10 00:07

myusuf3


People also ask

How do I schedule a cron job every second?

It's not possible to run cron in every second but we can run cron in every second using this method, we use a sleep command before the echo date. Cron - Cron is command name that runs scheduled action using the crond daemon.

What does cron 0 * * * * * mean?

*/5 * * * * Execute a cron job every 5 minutes. 0 * * * * Execute a cron job every hour.

Can we run cron every second?

Cron only allows for a minimum of one minute. What you could do is write a shell script with an infinite loop that runs your task, and then sleeps for 5 seconds. That way your task would be run more or less every 5 seconds, depending on how long the task itself takes.

What is the use of * * * * * In cron?

* * * * * is a cron schedule expression wildcard, meaning your cron job should run every minute of every hour of every day of every month, each day of the week.


2 Answers

I wouldn't use cron for this. I would use that bash script (use an absolute path, unless you want it to be portable and know that the directory structure will be preserved).

Instead, I would just sleep 5, just like you did (only 5 seconds instead of 1).

As far as starting it with your system, that depends on the system. On (some) Linux distros, there's a file called /etc/rc.local in which you can add scripts to run when the system starts. Well... I shouldn't be so general, the distros that I have used have this. If you're running Ubuntu, there is no longer an inittab, they use upstart, btw.

So if you have an endless loop and an entry in /etc/rc.local, then you should be golden for it to run endlessly (or until it encounters a problem and exits).

like image 103
TCCV Avatar answered Sep 24 '22 02:09

TCCV


Try using anacron or, better yet, an init script to start when the computer starts.

If you want the script to "restart itself", you'll need to run something every few minutes to check the original is still running. This can be done in inittab (/etc/inittab) or, on Ubuntu, /etc/event.d. Try man 5 inittab, looking at the 'respawn' option.

like image 40
Borealid Avatar answered Sep 23 '22 02:09

Borealid