Skip to content

Instantly share code, notes, and snippets.

@adrianomitre
Last active August 12, 2020 23:20
Show Gist options
  • Save adrianomitre/bc1fc3794dc63baea5c351bc3b12054e to your computer and use it in GitHub Desktop.
Save adrianomitre/bc1fc3794dc63baea5c351bc3b12054e to your computer and use it in GitHub Desktop.
Two approaches to schedule work with GenServer
defmodule Worker do
use GenServer
@delay 5
defp work(source) do
IO.puts("work from #{source}")
end
# Client
def start_link(state) do
GenServer.start_link(__MODULE__, state)
end
def schedule_work_1(server) do
Process.send_after(server, :work, @delay)
end
def schedule_work_2(server) do
spawn(fn ->
Process.sleep(@delay)
GenServer.cast(server, :work)
end)
end
# Server (callbacks)
@impl true
def handle_info(:work, state) do
work("handle_info")
{:noreply, state}
end
@impl true
def init(init_arg) do
{:ok, init_arg}
end
@impl true
def handle_cast(:work, state) do
work("handle_cast")
{:noreply, state}
end
end
{:ok, pid} = GenServer.start_link(Worker, nil)
timer_ref = Worker.schedule_work_1(pid)
pid = Worker.schedule_work_2(pid)
if false do
Process.cancel_timer(timer_ref)
Process.exit(pid, :kill)
end
Process.sleep(10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment