Skip to content

Instantly share code, notes, and snippets.

@minhajuddin
Created November 29, 2016 13:32
Show Gist options
  • Save minhajuddin/e083e2630959beb9616d894f5451ed9b to your computer and use it in GitHub Desktop.
Save minhajuddin/e083e2630959beb9616d894f5451ed9b to your computer and use it in GitHub Desktop.
A simple GenServer to do some work every few seconds
# Ticker
defmodule Ticker do
use GenServer
def start_link(%{module: module, function: function, interval: interval} = state)
when is_atom(module) and is_atom(function) and is_integer(interval) and interval > 0 do
GenServer.start_link(__MODULE__, state)
end
def init(state) do
send(self, :tick)
{:ok, state}
end
def handle_info(:tick, state) do
schedule_tick(state) # this makes sure that we catch up if a tick is delayed
work(state)
{:noreply, state}
end
defp work(%{module: module, function: function}) do
apply(module, function, [])
end
defp schedule_tick(state) do
Process.send_after(self, :tick, state.interval)
end
end
# Worker
defmodule Echo do
def work do
Enum.each(1..10,
fn _ -> IO.puts(".")
Process.sleep(100)
end)
end
end
# Application
defmodule Tickerx do
use Application
def start(_type, _args) do
import Supervisor.Spec, warn: false
children = [
worker(Ticker, [%{module: Echo, function: :work, interval: 3_000}]),
]
opts = [strategy: :one_for_one, name: Tickerx.Supervisor]
Supervisor.start_link(children, opts)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment