Created
May 3, 2015 14:40
-
-
Save gerred/e060fb1633f6bfd76be9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Timer do | |
use GenServer | |
@interval 10 * 1_000 | |
# Public API | |
defmodule State do | |
defstruct caller: nil, | |
timer: nil | |
end | |
def begin(caller) do | |
start_link(caller) | |
end | |
def start_link(caller) do | |
GenServer.start_link(__MODULE__, caller) | |
end | |
def reset(pid) do | |
GenServer.cast(pid, :reset) | |
end | |
# GenServer API | |
def init(caller) do | |
time_ref = :erlang.start_timer(@interval, self, :timeout) | |
{:ok, {caller, time_ref}} | |
end | |
def handle_cast(:reset, {caller, timer}) do | |
:erlang.cancel_timer(timer) | |
time_ref = :erlang.start_timer(@interval, self, :timeout) | |
{:noreply, {caller, time_ref}} | |
end | |
def handle_info({:timeout, _ref, :timeout}, {caller, timer}) do | |
:erlang.cancel_timer(timer) | |
time_ref = :erlang.start_timer(@interval, self, :timeout) | |
Kernel.send(caller, :timeout) | |
{:noreply, {caller, time_ref}} | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment