Skip to content

Instantly share code, notes, and snippets.

@zeroows
Forked from blackode/hello_server.ex
Created September 18, 2017 09:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zeroows/8d0c6aaef11f3e03c43867df64dc7d8e to your computer and use it in GitHub Desktop.
Save zeroows/8d0c6aaef11f3e03c43867df64dc7d8e to your computer and use it in GitHub Desktop.
GenServer Callbacks examples
defmodule HelloServer do
use GenServer
## Server API
def init(initial_value) do # initiating the state with the value 1 passed
{:ok,initial_value}
end
# add the value to the state and returns :ok
def handle_call({:add,value},_from,state) do
{:reply, "#{value} add",state + value}
end
# returns the state to the caller
def handle_call(:get,_from,state) do
:timer.sleep 2000
{:reply,state,state}
end
# just reset the state to value 1
def handle_cast(:reset,state) do
:timer.sleep 2000
IO.puts "value has been reset "
{:noreply,1}
end
# This executes periodically
def handle_info(:work,state) do
IO.puts " This message prints every after 2 seconds"
schedule_work()
{:noreply,state}
end
#catch-all clause for the handle_info for handling unkown messages
def handle_info(_msg, state) do
IO.puts "unknown message"
{:noreply, state}
end
defp schedule_work() do
Process.send_after(self(), :work, 2 * 1000) # In 2 seconds
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment