A timer module with microsend resolution.
MicroTimer
can sleep for as low as it takes to the BEAM
to send a message
(usually 3-5µ).
It can also send messages and invoke functions after a timeout
or repeatedly
every timeout
µs.
Keep in mind that the system sleep
primitive literally waits doing nothing, consuming no CPU whatsoever, while µsleep
is implemented with message passing
and wastes CPU cycles for a maximum of 2ms per call.
The CPU load shouldn't be a problem anyway, but it's definitely non-zero.
The package can be installed by adding micro_timer
to your list of dependencies in mix.exs
:
def deps do
[
{:micro_timer, "~> 0.1.0"}
]
end
MicroTimer has a very simple API
-
usleep(timeout)
and the aliasµsleep(timeout)
sleep fortimeout
µs. -
apply_after(timeout, executable, args \\ [])
invoke theexecutable
aftertimeout
µs with the argsargs
executable
can be the tuple{Module, :function}
or a function -
apply_every(timeout, executable, args \\ [])
invoke theexecutable
everytimeout
µs with the argsargs
-
send_after(timeout, message, pid \\ self())
sendmessage
aftertimeout
µs topid
ifpid
is empty, the message is sento toself()
-
send_every(timeout, message, pid \\ self())
sendmessage
everytimeout
µs topid
-
cancel_timer(timer)
cancel thetimer
created by one ofapply_after
,apply_every
,send_after
andsend_every
*_after
and *_avery
return a timer reference that is just a regular pid
.
You can check if the timer is still active or not with a simple call to Process.alive?(pid)
iex(1)> :timer.tc(fn -> MicroTimer.usleep(250) end)
{257, :ok}
iex(2)> MicroTimer.send_after(666, :msg)
#PID<0.222.0>
# approximately 666µs later
iex(3)> flush
:msg
:ok
Check out the examples
folder in this repository for more realistic examples.
Full documentation can be found at https://hexdocs.pm/micro_timer.
MicroTimer is released under the MIT License - see the LICENSE file.