Roman Kolesnikov
Roman Kolesnikov

Reputation: 12147

bash script: wait a few seconds since last run

How to write bash script that delays execution of its commands for a few seconds since it was run last time? I mean store somewhere last execution time, calculate diff to current time and then sleep, say 5 seconds, if last run was less than 5 secs away.

Upvotes: 0

Views: 2811

Answers (2)

terafl0ps
terafl0ps

Reputation: 704

The first question I would ask myself is, "Do I really need to delay the execution of the script for these commands?" If you can run multiple commands in parallel and then wait for each process to finish with the wait command, that is generally faster and preferable. Have a look at this SO question discussing the difference between wait and sleep

That said, you can do something like this if you really need to wait at least five seconds:

#!/bin/bash
export delay_seconds=5
export start_time=`date +%s`

#Run some commands here...

seconds_since_start=`expr \`date +%s\` - $start_time`

if [ $seconds_since_start -lt $delay_seconds ]; then
    time_remaining=`expr $delay_seconds - $seconds_since_start` 
    echo "Sleeping "$time_remaining" seconds..."
    sleep $time_remaining
else
    echo $seconds_since_start" seconds have already passed since the commands above started.  Continuing..."
fi

echo "Script finished."

Upvotes: 2

Roman Kolesnikov
Roman Kolesnikov

Reputation: 12147

In case someone needs it:

timeout=5
timefile=/tmp/dc-time.info
if [[ ! -e $timefile ]]; then
    touch $timefile
fi
old=`stat $timefile --format=%Y`
touch $timefile
new=`stat $timefile --format=%Y`
count=$((timeout-new+old))
if [ $count -gt 0 ]
then
    echo "waiting..."
    sleep $count
fi

Upvotes: 1

Related Questions