Sleep: Difference between revisions

From Leo's Notes
This page was last edited on 12 July 2021, at 23:09.
Created page with "<br /> == 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. {{High..."
 
No edit summary
Line 1: Line 1:
<br />
<br />


== Sleep to the nearest minute or hour ==
==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.
This can be done with some bash arithmetic and applying modulus to 60 seconds for 1 minute or 3600 seconds for 1 hour.
{{Highlight
{{Highlight
Line 12: Line 12:
}}
}}


=== With millisecond precision ===
===With millisecond precision===
If you need to synchronize a task by the millisecond, you can use <code>date +%s%N</code> which will print the timestamp with nanoseconds. Divide by 1000 for milliseconds and apply the same logic as above.
If you need to synchronize a task by the millisecond, you can use <code>date +%s%N</code> which will print the timestamp with nanoseconds. Divide by 1000 for milliseconds and apply the same logic as above.{{Highlight
<br />
| code = # Next minute
usleep $((60000 - (`date +%s%N` / 1000) % 60000 ))
 
# Next hour
usleep $((3600000 - (`date +%s%N` / 1000) % 3600000 ))
| lang = bash
}}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.

Revision as of 23:09, 12 July 2021


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.