Skip to content

Instantly share code, notes, and snippets.

@nathanl
Forked from trestrantham/periodic_task.ex
Created June 29, 2017 16:34
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 nathanl/1bae0cdcbd63259624f9a590f6d08984 to your computer and use it in GitHub Desktop.
Save nathanl/1bae0cdcbd63259624f9a590f6d08984 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