David
David

Reputation: 107

Script to run command at exactly X seconds past each minute

I'd like to run a bash script, for use on a Raspberry Pi, that says "if the seconds of the current time is exactly 00 or 30, then do X".

I've googled and found some suggestions to use cron, but I think there'd be a small delay at the start which I want to avoid.

Thanks

Upvotes: 1

Views: 385

Answers (1)

Leo Izen
Leo Izen

Reputation: 4289

If you don't like the delay of cron, which is mostly for background stuff, you could loop in the foreground:

while true; do
    d=$(date +%S)
    if [ $d -eq 0 -o $d -eq 30 ]; then
        # command here
        date +%S.%N
        # replace the above command with whatever you want
        sleep 5
    else
        sleep 0.001
    fi
done

The Linux date command can check the current system clock quite quickly. I've used this loop to print the nanosecond timer with data to demonstrate the low latency. That is, on my system, I get:

30.001057483
00.003022980
30.003011572

and so on.

Upvotes: 1

Related Questions