Continuous Looping in Linux Bash with Sleep

Here’s a snippet of my code that isn’t functional. The xterm window displays numerous lines, and the “Time” text from one line overlaps with the Info line. My objective is to run the application every X seconds, but since cron doesn’t support seconds, I created a bash script with a never-ending loop that includes a sleep command set to X seconds.

Question:

My objective is to perform a
PHP file
by running a
bash script
.

while true
do
    date1=$(date +%s%N | cut -b1-13)
    php /home/dkwogxax/public_html/sprint/yii hello/validate
    wait
    date2=$(date +%s%N | cut -b1-13)
    diff=$(($date2-$date1))
    echo "$diff ms"
done

When I use “diff”, the result I receive is the duration in milliseconds of
execution time
.

What steps can I take to guarantee that the
script sleeps
is fulfilled?

1200 - diff ms

How can we limit the number of times the PHP script is called within an hour to a maximum of 3000?


Solution:

Initially, a slumber is required, similar to the one present in GNU coreutils, which has the ability to recognize fractional seconds. Assuming you possess such a slumber, then:

sleep $(echo "1.2 - $diff/1000" | bc -l)

Another option is to streamline your loop as follows:

while true
do
        date1=$(date +%s%N)
        php /home/dkwogxax/public_html/sprint/yii hello/validate
        wait
        date2=$(date +%s%N)
        sleep $(echo "1.2 - ($date2-$date1)/1000000000" | bc -l)
done

Conversely, if we desire to retain a hard copy of the duration.

while true
do
        date1=$(date +%s%N)
        php /home/dkwogxax/public_html/sprint/yii hello/validate
        wait
        diff=$(echo "($(date +%s%N) - $date1)/1000000" | bc -l)
        echo "That took $diff milliseconds."
        time sleep $(echo "1.2 - ($diff)/1000" | bc -l)
done

Frequently Asked Questions