From Leo's Notes
Last edited on 30 December 2021, at 01:12.

Sleep is a command that sleeps for a certain amount of time. For millisecond sleeps, use usleep.

Sleep to the nearest minute or hour[edit | edit source]

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[edit | edit source]

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 back in 2017.