Last active
March 14, 2018 17:42
-
-
Save desmondmonster/c42ef495896449d689a48da51de9e628 to your computer and use it in GitHub Desktop.
Example of using a GenServer for recurring background work
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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