-
-
Save nathanl/1bae0cdcbd63259624f9a590f6d08984 to your computer and use it in GitHub Desktop.
Run a task periodically natively in Elixir
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 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