how to code a timer loop in a sh script

Polytropon freebsd at edvax.de
Sat Nov 11 08:32:36 UTC 2017


On Sat, 11 Nov 2017 18:15:35 +1030, Wayne Sierke wrote:
> 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.

An easy solution is the use of a lock file and [ -f for it,
prior to starting the execution. If there is no such file,
create it, then start executing, and finally remove it.
In this branch, checking for the time interval will happen.
Should another instance of the script be called during
the execution of the already running one, [ -f will
evaluate to true (as the file exists) and not enter the
branch for execution.



-- 
Polytropon
Magdeburg, Germany
Happy FreeBSD user since 4.0
Andra moi ennepe, Mousa, ...


More information about the freebsd-questions mailing list