Skip site navigation (1)Skip section navigation (2)
Date:      Sat, 11 Nov 2017 18:15:35 +1030
From:      Wayne Sierke <ws@au.dyndns.ws>
To:        Ernie Luzar <luzar722@gmail.com>, "freebsd-questions@freebsd.org" <freebsd-questions@freebsd.org>
Subject:   Re: how to code a timer loop in a sh script
Message-ID:  <1510386335.86602.2.camel@au.dyndns.ws>
In-Reply-To: <5A00A826.2000501@gmail.com>
References:  <5A00A826.2000501@gmail.com>

next in thread | previous in thread | raw e-mail | index | archive | help
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.




Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?1510386335.86602.2.camel>