how to code a timer loop in a sh script

Wayne Sierke ws at au.dyndns.ws
Sat Nov 11 07:50:53 UTC 2017


On Mon, 2017-11-06 at 13:21 -0500, Ernie Luzar wrote:
> Trying to write a sh script that will run continually and every 10 
> minutes issue a group of commands. Been trying to use the wait
> command 
> and the while loop command to achieve the desired effect with no
> joy. 
> Would like an example of a wait loop code to see how its done.
> 
> Thanks for any help.

Other answers have covered the "sleep X" inside the loop approach. One
potential shortcoming is that it accumulates the execution time of the
script. That is, if the time taken to execute the code in the loop is 1
minute, then the next execution will start 11 minutes after the time
that the previous execution started.

The following script records a timestamp and uses it to determine when
to execute the scheduled part.


#!/bin/sh
# see man date(1), -v option description
INTERVAL=600S ; # suffix is one of: y, m, w, d, H, M or S
# Set the initial scheduled time, delayed by $INTERVAL. 
# To adjust the initial delay, replace $INTERVAL with alternate value
nextruntime=$(date -v +$INTERVAL +%s)
while : ; do
        echo "executing main code (pre-scheduled)..."
        if [ $(date +%s) -ge $nextruntime ] ; then
                echo executing scheduled code... ; # scheduled code here
                nextruntime=$(date -r $nextruntime -v +$INTERVAL +%s)
        fi
        echo "executing main code (post-scheduled)..." ; sleep 1
done


One potential shortcoming of this is if the loop execution takes longer
than $INTERVAL, the scheduled code will get executed repeatedly until
it "catches up". When that is not desirable, a more sophisticated
handling of the timestamp can be used.



More information about the freebsd-questions mailing list