Skip to content

Instantly share code, notes, and snippets.

@trestrantham
Created January 27, 2016 05:19
Show Gist options
  • Save trestrantham/24f0892f2f6881474314 to your computer and use it in GitHub Desktop.
Save trestrantham/24f0892f2f6881474314 to your computer and use it in GitHub Desktop.
Run a task periodically natively in Elixir
defmodule MyApp.Periodically do
use GenServer
def start_link do
GenServer.start_link(__MODULE__, %{})
end
def init(state) do
Process.send_after(self(), :work, 2 * 60 * 60 * 1000) # In 2 hours
{:ok, state}
end
def handle_info(:work, state) do
# Do the work you desire here
# Start the timer again
Process.send_after(self(), :work, 2 * 60 * 60 * 1000) # In 2 hours
{:noreply, state}
end
end
# In the supervision tree:
worker(MyApp.Periodically, [])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment