Skip to content

Instantly share code, notes, and snippets.

@desmondmonster
Last active March 14, 2018 17:42
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 desmondmonster/c42ef495896449d689a48da51de9e628 to your computer and use it in GitHub Desktop.
Save desmondmonster/c42ef495896449d689a48da51de9e628 to your computer and use it in GitHub Desktop.
Example of using a GenServer for recurring background work
defmodule CryptoApp.AccountSync do
use GenServer
@interval 1_000
def start_link do
GenServer.start_link(__MODULE__, :ok, name: __MODULE__)
end
def init(:ok) do
Process.send_after(self(), :work, @interval)
{:ok, %{last_run_at: nil}}
end
def handle_info(:work, state) do
fetch_account_balance()
Process.send_after(self(), :work, @interval)
# by storing last_run_at in state we get basic monitoring via process inspection
# it's just for convenience - don't use this technique for sophisticated instrumentation
{:noreply, %{last_run_at: :calendar.local_time()}}
end
defp fetch_account_balance do
# your code here
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment