Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@cprieto
Created February 19, 2019 08:17
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 cprieto/8ade6af12db874d3043188cb4023bdcf to your computer and use it in GitHub Desktop.
Save cprieto/8ade6af12db874d3043188cb4023bdcf to your computer and use it in GitHub Desktop.

Write a simple server that sends a notification about every 2 seconds. To receive the notification, a client has to register with the server.

defmodule Ticker do
@interval 2000
@name :ticker
def run do
pid = spawn(__MODULE__, :generator, [[]])
:global.register_name(@name, pid)
end
def register(client_pid) do
send :global.whereis_name(@name), {:register, client_pid}
end
def generator(clients) do
receive do
{:register, pid} ->
IO.puts "registering #{inspect pid}"
generator([pid|clients])
after @interval
IO.puts "tick"
Enum.each clients, &(send &1, {:tick})
generator(clients)
end
end
end
defmodule Client do
def run do
pid = spawn(__MODULE__, :receiver, [])
Ticker.register(pid)
end
def receiver do
receive do
{:tick} ->
IO.puts "tock in client"
receiver()
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment