Sleep: Difference between revisions
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..." |
mNo edit summary |
||
| (2 intermediate revisions by the same user not shown) | |||
| Line 1: | Line 1: | ||
<br /> | <br />Sleep is a command that sleeps for a certain amount of time. For millisecond sleeps, use <code>usleep</code>. | ||
== 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 | ||
| 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 back in 2017. | |||
{{Navbox Linux}} | |||
[[Category:Linux]] | |||
[[Category:LinuxUtilities]] | |||
Latest revision as of 01:12, 30 December 2021
Sleep is a command that sleeps for a certain amount of time. For millisecond sleeps, use usleep.
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 back in 2017.