Sleep

From Leo's Notes
Revision as of 23:09, 12 July 2021 by Leo (talk | contribs)
This page was last edited on 12 July 2021, at 23:09.


Sleep to the nearest minute or hour

This can be done with some bash arithmetic and applying modulus to 60 seconds for 1 minute or 3600 seconds for 1 hour.

# Next minute
sleep $((60 - `date +%s` % 60))

# Next hour
sleep $((3600 - `date +%s` % 3600))

With millisecond precision

If you need to synchronize a task by the millisecond, you can use date +%s%N which will print the timestamp with nanoseconds. Divide by 1000 for milliseconds and apply the same logic as above.

# Next minute
usleep $((60000 - (`date +%s%N` / 1000) % 60000 ))

# Next hour
usleep $((3600000 - (`date +%s%N` / 1000) % 3600000 ))

Synchronizing bash scripts with this method works quite well as long as all the machines are using the same NTP server. I was able to precisely synchronize an audio file playing across an entire computer lab of over 100 machines through the PC speaker.